正则表达式匹配 string1 除非前面有 string2

发布于 2024-07-30 00:49:49 字数 111 浏览 4 评论 0原文

使用 Ruby,如何使用单个正则表达式来匹配“xy y ay xy +y”中所有前面没有 x (y, ay, +y) 的“y”?
/[^x]y/ 也匹配前面的字符,所以我需要一个替代方案......

Using Ruby, how can I use a single regex to match all occurrences of 'y' in "xy y ay xy +y" that are NOT preceded by x (y, ay, +y)?
/[^x]y/ matches the preceding character too, so I need an alternative...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(5

清旖 2024-08-06 00:49:49

不幸的是,Ruby 不支持负向后查找,因此如果您需要查找多个字符,就会遇到麻烦。 对于只有一个角色,您可以通过捕获匹配来解决这一问题:

/[^x](y)/

Ruby unfortunately doesn't support negative lookbehind, so you'll have trouble if you need to look for more than a single character. For just one character, you can take care of this by capturing the match:

/[^x](y)/
梦魇绽荼蘼 2024-08-06 00:49:49

您需要一个零宽度负后向断言。 尝试 /(? ,它准确地说明了您要查找的内容,即找到所有不以“x”开头的“y”,但不包括前面的字符,这是零宽度部分。

编辑添加:显然这仅支持 Ruby 1.9 及更高版本。

You need a zero-width negative look-behind assertion. Try /(?<!x)y/ which says exactly what you're looking for, i.e. find all 'y' not preceeded by 'x', but doesn't include the prior character, which is the zero-width part.

Edited to add: Apparently this is only supported from Ruby 1.9 and up.

偏爱你一生 2024-08-06 00:49:49

直到 Ruby 1.9 才支持负向后查找,但您可以使用 scan 执行类似的操作:

"xy y ay xy +y".scan(/([^x])(y)/) # => [[" ", "y"], ["a", "y"], ["+", "y"]]
"xy y ay xy +y".scan(/([^x])(y)/).map {|match| match[1]}  # => ["y", "y", "y"]

当然,如果您想避免 y 之前避免多个字符,那么这会困难得多。 然后你必须做类似的事情:

"abby y crabby bally +y".scan(/(.*?)(y)/).reject {|str| str[0] =~ /ab/}  # => [[" ", "y"], [" ball", "y"], [" +", "y"]]
"abby y crabby bally +y".scan(/(.*?)(y)/).reject {|str| str[0] =~ /ab/}.map {|match| match[1]}  # => ["y", "y" "y"]

Negative look-behind is not supported until Ruby 1.9, but you can do something similar using scan:

"xy y ay xy +y".scan(/([^x])(y)/) # => [[" ", "y"], ["a", "y"], ["+", "y"]]
"xy y ay xy +y".scan(/([^x])(y)/).map {|match| match[1]}  # => ["y", "y", "y"]

Of course, this is much more difficult if you want to avoid much more than a single character before the y. Then you'd have to do something like:

"abby y crabby bally +y".scan(/(.*?)(y)/).reject {|str| str[0] =~ /ab/}  # => [[" ", "y"], [" ball", "y"], [" +", "y"]]
"abby y crabby bally +y".scan(/(.*?)(y)/).reject {|str| str[0] =~ /ab/}.map {|match| match[1]}  # => ["y", "y" "y"]
望她远 2024-08-06 00:49:49

在 PCRE 中,您使用负向后查找:

(:<!x)y

不确定 Ruby 是否支持这一点,但您始终可以查找。

In PCRE, you use a negative look-behind:

(:<!x)y

Not sure if this is supported by Ruby, but you can always look up.

自找没趣 2024-08-06 00:49:49

这可以通过负向后看来完成,(?

It can be done with negative look behind, (?<!x)y

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