0

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

4
  • 1
    ^ is not operator. Try [0-9]+[\^]{1}[0-9]+ Commented May 17, 2013 at 20:55
  • You need to escape the caret - i.e. [/^] Commented May 17, 2013 at 20:56
  • Do you expect "1+1^2" to match at all? It won't if you fix the ^ issue. Commented May 17, 2013 at 20:56
  • 1
    @Imray Escaping should be done on the opposite side, using backslash [\]. Commented May 17, 2013 at 20:56

2 Answers 2

6

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]+/;

Fiddle

Sign up to request clarification or add additional context in comments.

5 Comments

[0-9]+\^[0-9]+ won't work - it needs 2 escape slashes: [0-9]+\\^[0-9]+
@Imray good point, but it will work in literal regex notation (/.../). Updated answer.
@Doorknob My problem is that i need it to work with multiple power calculation and this regex only seems to pick the first one it encounters even when using .match()
Note that ^ negates the character class only when it is at the start of the character class. It loses its meaning elsewhere
Ya but its about the character ^ not the regex sign
4

[^] 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/.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.