正则表达式匹配 string1 除非前面有 string2
使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不幸的是,Ruby 不支持负向后查找,因此如果您需要查找多个字符,就会遇到麻烦。 对于只有一个角色,您可以通过捕获匹配来解决这一问题:
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”,但不包括前面的字符,这是零宽度部分。
编辑添加:显然这仅支持 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.
直到 Ruby 1.9 才支持负向后查找,但您可以使用 scan 执行类似的操作:
当然,如果您想避免
y
之前避免多个字符,那么这会困难得多。 然后你必须做类似的事情:Negative look-behind is not supported until Ruby 1.9, but you can do something similar using scan:
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:在 PCRE 中,您使用负向后查找:
不确定 Ruby 是否支持这一点,但您始终可以查找。
In PCRE, you use a negative look-behind:
Not sure if this is supported by Ruby, but you can always look up.
这可以通过负向后看来完成,
(?
It can be done with negative look behind,
(?<!x)y