开发者

regex optional part in prefix, but do not include it in matches if it present

开发者 https://www.devze.com 2023-04-13 05:42 出处:网络
Problem is easier to be seen in code then described I got following regex (?<=First(Second)?)\\w{5}

Problem is easier to be seen in code then described I got following regex

 (?<=First(Second)?)\w{5}

and following sample data

FirstSecondText1

FirstText2

I only want开发者_Python百科 matches Text1 & Text2 , I get 3 though, Secon is added, and I don't want that. Played around, cant seem to get it to work.


You need an additional negative lookahead:

(?<=First(Second)?)(?!Second)\w{5}

If you want to avoid using Second twice, you could do it without lookaround and take the result of the first capturing group:

First(?:Second)?(\w{5})


You can try this regex (?<=First(Second)?)\w{5}$. All you have to do is to add a $ in the end so that the regex would not match the text Secon. You can use this as long as you are sure of the pattern that comes at the end of the input text. In this case it is \w{5}$

0

精彩评论

暂无评论...
验证码 换一张
取 消