开发者

Regex for number surrounded by slashes

Like the title says, I have a (faulty) Regex in Jav开发者_JAVA百科aScript, that should check for a "2" character (in this case) surrounded by slashes. So if the URL was http://localhost/page/2/ the Regex would pass.

In my case I have something like http://localhost/?page=2 and the Regex still passes.

I'm not sure why. Could anyone tell me what's wrong with it?

/^(.*?)\b2\b(.*?$)/

(I'm going to tell you, I didn't write this code and I have no idea how it works, cause I'm really bad with Regex)


Seems too simple but shouldn't this work?:

/\/2\// 

http://jsfiddle.net/QHac8/1/

As it's javascript you have to escape the forward slashes as they are the delimiters for a regex string.

or if you want to match any number:

/\/\d+\// 


You don't check for a digit surrounded by slashes. The slashes you see are only your regex delimiters. You check for a 2 with a word boundary \b on each side. This is true for /2/ but also for =2

If you want to allow only a 2 surrounded by slashes try this

/^(.*?)\/2\/(.*?)$/

^ means match from the start of the string

$ match till the end of the string

(.*?) those parts are matching everything before and after your 2 and those parts are stored in capturing groups.

If you don't need those parts, then Richard D is right and the regex /\/2\// is fine for you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜