Lazy quantifier {,}? not working as I would expect

前端 未结 3 398
忘了有多久
忘了有多久 2020-12-04 02:37

I have an issue with lazy quantifiers. Or most likely I misunderstand how I am supposed to use them.

Testing on Regex101 My test string is let\'s say: 12345678

3条回答
  •  既然无缘
    2020-12-04 03:06

    Your regex is

    .{1,5}?D
    

    matches

    123456789D123456789
        ------
    

    But you said you expected 9D because using of "non-greedy quantifier".

    Anyway, how about this?

    D.{1,5}?
    

    What is a result of matching?

    Yes! as you expected it matches

    123456789D123456789
             --
    

    So, WHY?

    OK, The first, I think you need to understand that normally regex engine will read characters from left to right-hand side of an input string. Considering your example which using non-greedy quantifier, once engine is matched

    123456789D123456789
        ------
    

    It will not go further to

    123456789D123456789
         -----
    123456789D123456789
          ----
    ...
    123456789D123456789
            --
    

    Because regex engine will evaluate text as less as possible, this is why it also called "Lazy quantifiers".

    And it also work in the same way on my regex D.{1,5}? which should not go further to

    123456789D123456789
             ---
    123456789D123456789
             ----
    ...
    123456789D123456789
             ------
    

    But stop at the first match

    123456789D123456789
             --
    

提交回复
热议问题