斜杠包围数字的正则表达式
就像标题所说,我在 JavaScript 中有一个(错误的)正则表达式,它应该检查斜杠包围的“2”字符(在本例中)。因此,如果 URL 为 http://localhost/page/2/ 则正则表达式将通过。
就我而言,我有类似 http://localhost/?page=2 的内容,正则表达式仍然通过。
我不知道为什么。谁能告诉我有什么问题吗?
/^(.*?)\b2\b(.*?$)/
(我要告诉你,我没有写这段代码,我不知道它是如何工作的,因为我对正则表达式真的很糟糕)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看起来太简单了,但这不应该起作用吗?
: http://jsfiddle.net/QHac8/1/
因为它是 javascript,所以你必须转义正斜杠,因为它们是正则表达式字符串的分隔符。
或者如果你想匹配任何数字:
Seems too simple but shouldn't this work?:
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:
您不检查斜线包围的数字。您看到的斜杠只是您的正则表达式分隔符。检查每边是否有单词边界
\b
的 2。对于/2/
如此,对于=2
也是如此。如果您只想允许斜杠包围的 2,请尝试使用此
^
表示匹配字符串$
的开头匹配,直到字符串(.*?)
的结尾,这些部分匹配
2
之前和之后的所有内容,并且这些部分存储在捕获组中。如果您不需要这些部分,那么 Richard D 是对的,正则表达式
/\/2\//
适合您。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
^
means match from the start of the string$
match till the end of the string(.*?)
those parts are matching everything before and after your2
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.