Like the title says, I have a (faulty) Regex in JavaScript, 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)
Like the title says, I have a (faulty) Regex in JavaScript, 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)
Share Improve this question asked Sep 28, 2011 at 8:55 Eduard LucaEduard Luca 6,61218 gold badges88 silver badges142 bronze badges 4-
1
Your regexp should look like
/\d+/
– user684934 Commented Sep 28, 2011 at 9:01 -
1
It's looking for a
2
surrounded by\b
's which are word boundaries. So as long as the2
character is considered a "word" it will match. The(.*?)
just grab the surrounding text (greedily), presumably so you can rebuild the URL. – davin Commented Sep 28, 2011 at 9:02 - try losing the question marks.. ^(.*) should be sufficient if you want to match any starting sequence.. – Nanda Commented Sep 28, 2011 at 9:02
- Accidentally voted for bdares's ment, which is wrong. – Lightness Races in Orbit Commented Sep 28, 2011 at 9:11
2 Answers
Reset to default 6Seems too simple but shouldn't this work?:
/\/2\//
http://jsfiddle/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.