Why the positive lookahead not working for this regex [closed]

徘徊边缘 提交于 2019-12-20 07:55:15

问题


This is my regex

^(settings|issues(?=a))/$

I want to match settings/ and issuesa/. The problem is I am only able to match settings/ and not issuesa/.


回答1:


The “a” in the lookahead is not part of the match.

It would match if the regex was

^(settings|issues(?=a))a/$

(though it would not match settings/ then)

or

^(settings|issues(?=a)a)/$

(but then I don't see a point for the lookahead).




回答2:


Try it

regex = '^(settings|issues(a*))/$'

You can also look it up here how regex works: https://regex101.com/r/vQr5cP/1




回答3:


With (?=a), you require a to appear at the same location in the string as /. Since / can't be a, issues(?=a) will always fail to match.

You need to put all the right-hand boundaries into lookahead constructs:

^(settings(?=/$)|issues(?=a/$))

See the regex demo

Details

  • ^ - start of string
  • (settings(?=/$)|issues(?=a/$)) - Capturing group 1:
    • settings(?=/$) - settings substring that is immediately followed with / and end of string position
    • | - or
    • issues(?=a/$) - issues substring that is immediately followed with a/ and end of string position.


来源:https://stackoverflow.com/questions/59299644/why-the-positive-lookahead-not-working-for-this-regex

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