正则表达式“/^某事/”行为
在一些模糊的情况下,像“/^match/”这样的正则表达式以完全相反的方式匹配“其他”的行,解决它的唯一方法是将整个正则表达式放在大括号内...“/ ^(match)/",为什么会发生这种情况?
In some obscure situations a regular expression like "/^match/" works in the exact oposite way matching a line that is "something else", and the only way to fix it is to put the whole regex inside braces ... "/^(match)/", why is that happening?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这里只是一个疯狂的猜测......我能想到的唯一一个例子会给出您所描述的行为正在改变:
注意
,括号的添加改变了这个正则表达式的含义。第二个匹配字符串开头的 foo 或 bar。第一个匹配字符串开头的 foo 或字符串中任何位置的 bar 。正如您所描述的,这可能会产生一些错误的匹配。
忘记那些括号是一个很容易的错误...我有时也这样做过...脸红...;)
我现在想不出任何其他例子,但我确信可能还有其他时候当添加括号时,含义会发生微妙的变化。下次,请记住保存您找到的示例并将其发布到此处,以便我们可以看到。
Just a wild guess here... the only example I can think of that would give the behaviour you describe is changing:
to
Note that the addition of parentheses changes the meaning of this regular expression. The second matches foo or bar at the beginning of the string. The first matches foo at the beginning of the string or bar anywhere in the string. This might give some false matches as you described.
It's an easy mistake to forget those parentheses... I've done it on occasion too ...blush... ;)
I can't think of any other examples right now, but I'm sure there might be other times when the addition of parentheses gives a subtle change in meaning. Next time, remember to save the example you found and post it here so we can see it.
完全随机猜测,但是您是否在
split
中使用它?在 javascript 中(我对 PHP 不太确定),如果我输入:
"matchabc".split(/^match/)
我得到:
["", "abc"]
请注意,split 使用匹配来划分字符串,因此您会得到不匹配的部分。
但是,如果我这样做:
"matchabc".split(/^(match)/)
我得到:
["", "match", "abc"]
这就是因为括号捕获了我要拆分的内容。这听起来有点像您所描述的行为——如果您发布一个说明问题的示例(不仅仅是正则表达式,还有您如何使用它以及它所作用的字符串),会更容易判断。
Totally random guess, but were you using it in a
split
?In javascript (I'm not as sure about PHP), if I type this:
"matchabc".split(/^match/)
I get:
["", "abc"]
Note that split uses the match to divide up the string, so you get the pieces that don't match.
However, if I do this:
"matchabc".split(/^(match)/)
I get:
["", "match", "abc"]
That's because the parentheses capture the thing I'm splitting on. This sounds a little like the behavior you're describing -- it'd be easier to tell if you post an example that illustrates the issue (not just the regex, but how you're using it and the string it's acting on).