regex and javascript
using http://www.regular-expressions.info/javascriptexample.html I tested the following regex
^\\{1}([0-9])开发者_C百科+
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?
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
.
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+)
.
精彩评论