views:

52

answers:

2

using http://www.regular-expressions.info/javascriptexample.html I tested the following regex

 ^\\{1}([0-9])+ 

this is designed to match a backslash and then a number.

It works there

If I then try this directly in code

var reg = /^\\{1}([0-9])+/;
reg.exec("/123")

I get no matches!

What am I doing wrong?

+2  A: 

You need to escape the backslash in your string:

"\\123"

Also, for various implementation bugs, you may want to set reg.lastIndex = 0;. In addition, {1} is completely redundant, you can simplify your regex to /^\\(\d)+/.
One last note: (\d)+ will only capture the last digit, you may want (\d+).

Kobi
that was a typo in the post!I've updated it!
lehelp
@lehelp - Your post still shows without the ` \ `, right now your `reg.exec("\123")` is escaping the `1`, not acting as a backslash. - Wow didn't realize I had to escape it in the damn comment as well heh.
Nick Craver
@Nick: The typo was a `/` instead of `\ ` (see sje397's comment). Kobi updated his answer in the meantime.
Felix Kling
@Felix - Ahh gotcha
Nick Craver
You were right the first time.I actually WANTED to test /123my regex was testing \123:)
lehelp
+5  A: 

Update:

Regarding the update of your question. Then the regex has to be:

var reg = /^\/(\d+)/;

You have to escape the slash inside the regex with \/.


The backslash needs to be escaped in the string too:

reg.exec("\\123")

Otherwise \1 will be treated as special character.

Btw, the regular expression can be simplified:

var reg = /^\\(\d+)/;

Note that I moved the quantifier + inside the capture group, otherwise it will only capture a single digit (namely 3) and not the whole number 123.

Felix Kling
Any reason why you are not using (?:....)?
Anders
@Anders - if you don't want to capture, you can use `^\\\d+` - you don't need a group at all.
Kobi