负面观察中的替代品

时间:2014-09-30 22:02:12

标签: ruby regex

我希望匹配一个前面没有"]: ""("的字符串。首先,我尝试一次只使用一个标准的后视语法,它可以工作:

/(?<!\]: )\b(.+)/i

/(?<!\()\b(.+)/i

然后,当我尝试使用后视中的或语法组合两个条件时,它会中断:

/(?<!(\]: |\())\b(.+)/i

我收到错误说:

RegexpError: invalid pattern in look-behind

是否有类似Regexp.union的内容需要字符串来匹配所有表达式?任何建议都将不胜感激。

2 个答案:

答案 0 :(得分:1)

你可以使用两个连续的lookbehinds:

(?<!\()(?<!\]: )\b(.+)

答案 1 :(得分:0)

来自Oniguruma manual

(?<=subexp)        look-behind
(?<!subexp)        negative look-behind

                     Subexp of look-behind must be fixed character length.
                     [D]ifferent character length is allowed in top level
                     alternatives only.
                     ex. (?<=a|bc) is OK. (?<=aaa(?:b|cd)) is not allowed.

                     In negative-look-behind, captured group isn't allowed, 
                     but shy group(?:) is allowed.

所以只需用害羞的小组替换被捕获的小组:

/(?<!(?:\]: |\())\b(.+)/i