Issue with a Look-behind Regular expression (Ruby)

放肆的年华 提交于 2019-12-29 08:31:47

问题


I wrote this regex to match all href and src links in an HTML page; (I know I should be using a parser; this just experimenting):

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

It works fine, but when I try to modify the first portion of the expression as a look-behind pattern:

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

It throws an error stating 'invalid look-behind pattern'. Any ideas, whats going wrong with the look-behind?


回答1:


Lookbehind has 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.

You cannot put alternatives in a non-top level within a (negative) lookbehind.

Put them at the top level. You also don't need to escape some characters that you did.

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


来源:https://stackoverflow.com/questions/19947331/issue-with-a-look-behind-regular-expression-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!