views:

47

answers:

3

I am trying use javascript regular expressions to do some matching and I found a really unusual behavior that I was hoping someone could explain.

The string I was trying to match was: " 0 (IR) " and the code block was

finalRegEx = new RegExp("[0-9]");
match = finalRegEx.exec(str);

except that when I put "\d" instead of "[0-9]" it didn't find a match. I'm really confused by this.

+3  A: 

You need to escape it because you're using the constructor, otherwise it matches d literally:

new RegExp('\\d').test('1')

new RegExp should only be used for dynamic matching. Otherwise use a literal:

var foo = /\d/;
foo.test(1)
meder
what do you mean by dynamic matching? matching against the contents of a variable?
lincolnk
creating the regex dynamically instead of hard coding it, such as in a loop, creating a new RegExp object per some changing variable.
meder
+3  A: 

If you use RegExp with "\d" to build the regular expression, the "\d" will result in just "d". Either use two back slashes to escape the slash like "\\d" or simply use the regular expression literals /…/ instead:

match = /\d/.exec(str)
Gumbo
A: 

You probably need to escape the backslash: finalRegEx = new RegExp("\\d");

Dan Breen