I have this simple regex that is supposed to match any numbers and '+' signs
/^[\d\+]+$/g
What it does is this:
1 => true
11 => false
11+11 => true
1+1 => false
It's driving me nuts!
(I'm using JavaScript, if it matters)
I have this simple regex that is supposed to match any numbers and '+' signs
/^[\d\+]+$/g
What it does is this:
1 => true
11 => false
11+11 => true
1+1 => false
It's driving me nuts!
(I'm using JavaScript, if it matters)
Some assumptions I did when reproducing your error:
test()
-method of the RegExp
-prototype, not the match()
-method of the String
-prototype.test()
-method.At a first glance, the result is somewhat unexpected, but I'll try to explain what is happening.
Your RegExp has the global-Flag set to true. This causes subsequent calls to the test()
-method to advance past previous matches, as stated here. This essentially means that after your first regular expression is evaluated and a match was found, the index of this match is stored into the RegExp
-object and the next match will start at that very index, omitting some characters at the beginning. For a deeper explanation, I'd recommend reading this thread.
This is not really what you want, right? My quick recommendation would be to simply remove the global-flag, as you don't really need it from my point of view. If you want to ensure that your regular expression is only matching full strings rather than substrings, use the ^
and $
metacharacters (as you already did).
EDIT:
If you really need the global-flag though, try to use the match()
-method of the String
-prototype, as it does not advance past previous matches. Instead it uses the advancing feature and captures all matches, resetting the index afterwards.
var pattern = /^[\d\+]+$/g;
"1".match(pattern); // => true
"11+11".match(pattern); // => true
"1+1abc".match(pattern); // => false