正则表达式“/^某事/”行为

发布于 2024-08-20 11:23:45 字数 104 浏览 3 评论 0原文

在一些模糊的情况下,像“/^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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

半城柳色半声笛 2024-08-27 11:23:45

这里只是一个疯狂的猜测......我能想到的唯一一个例子会给出您所描述的行为正在改变:

/^foo|bar/

注意

/^(foo|bar)/

,括号的添加改变了这个正则表达式的含义。第二个匹配字符串开头的 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:

/^foo|bar/

to

/^(foo|bar)/

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.

酒绊 2024-08-27 11:23:45

完全随机猜测,但是您是否在 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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文