【问题标题】:Issue with a Look-behind Regular expression (Ruby)后视正则表达式 (Ruby) 的问题
【发布时间】:2013-11-13 06:56:36
【问题描述】:

我编写了这个正则表达式来匹配 HTML 页面中的所有 hrefsrc 链接; (我知道我应该使用解析器;这只是试验):

/((href|src)\=\").*?\"/#Without look-behind

效果很好,但是当我尝试将表达式的第一部分修改为后视模式时:

/(?<=(href|src)\=\").*?\"/#With look-behind

它会抛出一个错误,指出“无效的后视模式”。有什么想法,后视有什么问题?

【问题讨论】:

标签: ruby regex lookbehind


【解决方案1】:

Lookbehind 有restrictions:

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

                      Subexp of look-behind must be fixed character length.
                      But different 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.

您不能在(负面)回顾中将替代品放在非顶级。

将它们放在顶层。您也不需要转义您所做的某些字符。

/(?<=href="|src=").*?"/

【讨论】:

  • 哦,谢谢!不知道有这样的规定!也感谢 Oniguruma 备忘单!虽然,与概念不太相关:上述问题可以通过像这样修改后面的负面外观来解决,因此字符长度相同:/(?&lt;=(?:ref|src)\=\").*?\"/
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-29
  • 1970-01-01
  • 1970-01-01
  • 2014-07-09
  • 1970-01-01
相关资源
最近更新 更多