Reputation: 11
Im trying to get all the power calculations out of a string using reg exp's i tried the following code:
var regex = new RegExp('[0-9]+[^]{1}[0-9]+');
regex.exec('1^2');
this works and returns 1^2 but when i try to use the following string:
regex.exec('1+1^2');
it returns 1+1
Upvotes: 0
Views: 83
Reputation: 59363
This is because [^xyz]
means "not x, y, or z." ^
is the "not" operator in character classes ([...]
). To fix this, simply escape it (one backslash to escape the ^
, and another to escape the first backslash since it's in a string and it's a special character):
var regex = new RegExp('[0-9]+[\\^]{1}[0-9]+');
Also, you don't need to use character classes and the {1}
if you only have one character; just do this:
var regex = new RegExp('[0-9]+\\^[0-9]+');
Finally, one more improvement - you can use literal regular expression syntax (/.../
) so you don't need two backslashes:
var regex = /[0-9]+\^[0-9]+/;
Upvotes: 6
Reputation: 360872
[^]
in regex terms is a character class ([]
) that's been inverted (^
). e.g. [^abc]
is "any character that is NOT a, b, or c". You need to escape the carat: [\^]
.
As well, {1}
is redundant. Any character class or individual character in a regex has an implied {1}
on it, so /a{1}b{1}c{1}/
is just a very verbose way of saying /abc/
.
As well, a single-char character class is also redundant. /[a]/
is exactly the same as /a/
.
Upvotes: 4