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?

3
  • Isn't that a forward slash in the second line? Commented Jul 18, 2010 at 10:45
  • 1
    Any specific reason you are not using match(), developer.mozilla.org/en/… ? Commented Jul 18, 2010 at 10:53
  • actually I was being an idiot. I wanted to match /123 so I needed something like /^\/{1}([0-9]+)$/ Commented Jul 18, 2010 at 11:11

2 Answers 2

5

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.

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

1 Comment

@Anders - if you don't want to capture, you can use ^\\\d+ - you don't need a group at all.
2

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+).

3 Comments

@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: The typo was a / instead of \ (see sje397's comment). Kobi updated his answer in the meantime.
You were right the first time. I actually WANTED to test /123 my regex was testing \123 :)

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.