Regex lazy vs greedy confusion

后端 未结 2 1155
一个人的身影
一个人的身影 2020-11-29 12:29

I\'m a little confused about regular expressions and greedy vs lazy. It\'s really very simple and it feels like I\'m missing something obvious.

I\'ve simplified my p

2条回答
  •  不知归路
    2020-11-29 13:29

    user1277327, the (?<=a) part of your pattern means "preceded by an 'a'". When the regex engine starts on your string aaxxxb, the first "a" doesn't fulfill the assertion of that lookbehind, but the second "a" does. Fine, but can the engine match that "a"? Yes, the dot in your .* allows the engine to match this "a". The lazy modifier ? tells the dot star to eat up only as many characters as necessary until we are able to match what comes next. What comes next is a lookahead asserting that the next character is a "b". So the engine eats up the three x characters. The total match is axxx.

    If you are finding greed / laziness confusing, you may want to have a look at the levels of regex greed. The accompanying tut on lookarounds may also help.

提交回复
热议问题