I have been using the RegEx /[ -~]/i in JavaScript for a while now and found that it works well testing for any ASCII character including the space. Today I accidentally used /^[ -~]$/i and found much to my surprise that /^[ -~]$/i.test('Stackoverflow is great') failed owing to the space character. My understanding of Regexes is rather limited but even so I fail to see what I might be doing wrong here. Perhaps somone here can shed some light on what is happening?
You miss a quantifier, a + or *:
alert(/^[ -~]*$/i.test('Stackoverflow is great'));
Without the quantifier a character class just matches 1 symbol. You need that quantifier in this case because you added anchors that require matching at the beginning of the string (^) and at the string end ($).
Note that * means match 0 or more occurrences of the preceding subpattern, and + matches 1 or more occurrences.
And it is true as for what your regex matches as the hyphen creates a range between a space and a tilde:
Related
I'm having trouble with a certain RegEx replacement string for later use in Javascript.
We have quite a bit of text that was stored in a rather odd format that we aren't allowed to fix.
But we do need to find all the "network path" strings inside it, following these rules:
A. The matches always start with 2 backslashes.
B. The matching characters should stop as soon as it hits a first occurrence of any 1 of these:
A < character
A space
A line feed
A carriage return
A & character
A literal "\r" or "\n" string (but only if occurring at end of line)
We "almost" have it working with /\\\\[^ &<\s]*/gi as shown in this RegEx Tester page:
https://regex101.com/r/T4cDOL/5
Even if we get it working, the RegEx has to be even futher "escape escaped" before putting on
our Javascript code, but that's also not working as expected.
From your example, it seems you literally have a backslash followed by an n and a backslash followed by an r (as opposed to a newline or carriage return), which means you can't only use a negated character class (since you need to handle a sequence of two characters). I'd use a positive lookahead to know where to stop, so I can use an alternation for that part.
You haven't said what parts of those strings should match, so I've had to guess a bit, but here's my best guess (with useful input from Niet the Dark Absol):
const rex = /\\\\.*?(?=[ &<\r\n]|\\[rn](?:$| ))/gmi;
That says:
Match starting with \\
Take everything prior to the lookahead (non-greedy)
Lookahead: An alternation of:
A space, &, <, carriage return (\r, character 13), or a newline (\n, character 10); or
A backslash followed by r or n if that's either at the end of a line or followed by a space (so we get the \nancy but not the \n after it).
Updated regex101
You might want to have more characters than just a space after the \r/\n. If so, make it a character class (and/or use \s for "whitespace" if that applies):
const rex = /\\\\.*?(?=[ &<\r\n]|\\[rn](?:$|[ others]))/gmi;
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^
I'm currently trying to match the following cases with Regex.
Current regex
\.\/[^/]\satoms\s\/[^/]+\/index\.js
Cases
// Should match
./atoms/someComponent/index.js
./molecules/someComponent/index.js
./organisms/someComponent/index.js
// Should not match
./atomsdsd/someComponent/index.js
./atosdfms/someComponent/index.js
./atomssss/someComponent/index.js
However none of the cases are matching, what am I doing wrong?
Hope this will help you out. You have added some addition characters which lets your regex to fail.
Regex: \.\/(atoms|molecules|organisms)\/[^\/]+\/index\.js
1. \.\/ This will match ./
2. (atoms|molecules|organisms) This will match either atoms or molecules or organisms
3. \/[^\/]+\/ This will match / and then till /
4. index\.js This will match index.js
Regex demo
why not just this simpler pattern?
\.\/(atoms|molecules|organisms)\/.*?index\.js
Try the following:
\.\/(atoms|molecules|organisms)\/[a-zA-Z]*\/index\.js
Forward slashes (and other special characters) should be escaped with a back slash \.
\.\/(atoms|molecules|organisms)\/ matches '.atoms/' or .molecules or organisms strictly. Without the parenthesis it will match partial strings. the | is an alternation operator that matches either everything to the left or everything to the right.
[a-zA-Z]* will match a string of any length with characters in any case. a-z accounts for lower case while A-Z accounts for upper case. * indicates one or more characters. Depending on what characters may be in someCompenent you may need to account for numbers using [a-zA-Z\d]*.
\/index\.js will match '/index.js'
Thanks for taking a look.
My goal is to come up with a regexp that will match input that contains no digits, whitespace or the symbols !#£$%^&*()+= or any other symbol I may choose.
I am however struggling to grasp precisely how regular expressions work.
I started out with the simple pattern /\D/, which from my understanding will match the first non-digit character it can find. This would match the string 'James' which is correct but also 'James1' which I don't want.
So, my understanding is that if I want to ensure that a pattern is not found anywhere in a given string, I use the ^ and $ characters, as in /^\D$/. Now because this will only match a single character that is not a digit, I needed to use + to specify that 1 or more digits should not be founds in the entire string, giving me the expression /^\D+$/. Brilliant, it no longer matches 'James1'.
Question 1
Is my reasoning up to this point correct?
The next requirement was to ensure no whitespace is in the given string. \s will match a single whitespace and [^\s] will match the first non-whitespace character. So, from my understanding I just had to add this to what I have already to match strings that contain no digits and no whitespace. Again, because [^\s] will only match a single non-white space character, I used + to match one or more whitespace characters, giving the new regexp of /^\D+[^\s]+$/.
This is where I got lost, as the expression now matches 'James1' or even 'James Smith25'. What? Massively confused at this point.
Question 2
Why is /^\D+[^\s]+$/ matching strings that contain spaces?
Question 3
How would I go about writing the regular expression I'm trying to solve?
While I am keen to solve the problem I am more interested in figuring where my understanding of regular expressions is lacking, so any explanations would be helpful.
Not quite; ^ and $ are actually "anchors" - they mean "start" and "end", it's actually a little more complicated, but you can consider them to mean the start and end of a line for now - look up the various modifiers on regular expressions if you're interested in learning more about this. Unfortunately ^ has an overloaded meaning; if used inside square brackets it means "not", which is the meaning you are already acquainted with. It's very important that you understand the difference between these two meanings and that the definition in your head actually applies only to character range matching!
Contributing further to your confusion is that \d means "a numerical digit" and \D means "not a numerical digit". Similarly \s means "a whitespace (space/tab/newline/etc.) character" and \S means "not a whitespace character."
It's worth noting that \d is effectively a shortcut for [0-9] (note that - has a special meaning inside square brackets), and \D is a shortcut for [^0-9].
The reason it's matching strings that contain spaces is that you've asked for "1+ non-numerical digits followed by 1+ non-space characters" - so it'll match lots of strings! I think that perhaps you don't understand that regular expressions match bits of strings, you're not adding constraints as you go, but rather building up bots of matchers that will match bits of corresponding strings.
/^[^\d\s!#£$%^&*()+=]+$/ is the answer you're looking for - I'd look at it like this:
i. [] - match a range of characters
ii. []+ - match one or more of that range of characters
iii. [^\d\s]+ - match one or more characters that do not match \d (numerical digit) or \s (whitespace)
iv. [^\d\s!#£$%^&*()+=]+ - here's a bunch of other characters I don't want you to match
v. ^[^\d\s!#£$%^&*()+=]+$ - now there are anchors applied, so this matcher has to apply to the whole line otherwise it fails to match
A useful website to explore regexs is http://regexr.com/3b9h7 - which I supply with my suggested solution as an example. Edit: Pruthvi Raj's link to debuggerx is awesome!
Is my reasoning up to this point correct?
Almost. /\D/ matches any character other than a digit, but not just the first one (if you use g option).
and [^\s] will match the first non-whitespace character
Almost, [^\s] will match any non-whitespace character, not just the first one (if you use g option).
/^\D+[^\s]+$/ matching strings that contain spaces?
Yes, it does, because \D matches a space (space is not a digit).
Why is /^\D+[^\s]+$/ matching strings that contain spaces?
Because \D+ in /^\D+[^\s]+$/can match spaces.
Conclusion:
Use
^[^\d\s!#£$%^&*()+=]+$
It will match strings that have no digits and spaces, and the symbols you do not allow.
Mind that to match a literal -, ] or [ with a character class, you either need to escape them, or use at the start or end of the expression. To play it safe, escape them.
Just insert every character you don't want to include in a negated character class as follows:
^[^\s\d!#£$%^&*()+=]*$
DEMO
Debuggex Demo
^ - start of the string
[^...] - matches one character that is not in `...`
\s - matches a whitespace (space, newline,tab)
\d - matches a digit from 0 to 9
* - a quantifier that repeats immediately preceeding element by 0 or more times
so the regex matches any string that has
1. string that has a beginning
2. containing 0 or more number of characters that is not whitesapce, digit, and all the symbols included in the character class ( In this example !#£$%^&*()+=) i.e., characters that are not included in the character class `[...]`
3.that has ending
NOTE:
If the symbols you don't want it to have also includes - , a hyphen, don't put it in between some other characters because it is a metacharacter in character class, put it at last of character class
I'm trying to write a RegEx that returns true if the string starts with / or http: and only allows alpha numeric characters, the dash and underscore. Any white space and any other special characters should fire a false response when tested.
Below works fine (except that it allows special characters, I have not figured out how to do that yet) when tested at https://www.regex101.com/#javascript. Unfortunately returns false when I implement it in my site and test it with /products/homedecor/tablecloths. What am I doing wrong and is there a better regEx to use that would accomplish my goals?
^(\\/|(?:http:))\S+[a-zA-Z0-9-_]+$
Keep unescaped hyphen at first or at last position in character class:
^(\/|(?:http:))[/.a-zA-Z0-9_-]+$
Or even simpler:
^(\/|http:)[/\w.-]+$
Since \w is same as [a-zA-Z0-9_]
To match URL you may need to match DOT and forward slash as well.
Just remove the \S+ from your regex and put the hyphen inside the character class at the first or at the last. Note that \S+ matches any non-space characters (including non-word characters).
^(\/|http:)[a-zA-Z0-9_-]+$
I have looked through previous questions and answers, however they do not solve the following:
https://stackoverflow.com/questions/ask#notHashTag
The closest I got to is this: (^#|(?:\s)#)(\w+), which finds the hashtag in half the necessary cases and also includes the leading space in the returned text. Here are all the cases that need to be matched:
#hashtag
a #hashtag
a #hashtag world
cool.#hashtag
##hashtag, but only until the comma and starting at second hash
#hashtag#hashtag two separate matches
And these should be skipped:
https://stackoverflow.com/questions/ask#notHashTag
Word#notHashTag
#ab is too short to be a hashtag, 3 characters minimum
This should work for everything but #hashtag#duplicates, and because JS doesn't support lookbehind, that's probably not possible to match that by itself.
\B#\w{3,}
\B is designed to match only between two word characters or two non-word characters. Since # is a non-word character, this forces the match to be preceded by a space or punctuation, or the beginning of the string.
Try this regex:
(?:^|[\s.])(#+\w{3,})(#+\w{3,})?
Online Demo: http://regex101.com/r/kG1nD5