How does the ? make a quantifier lazy in regex

后端 未结 4 1529
忘了有多久
忘了有多久 2020-12-06 07:56

I\'ve been looking into regex lately and figured that the ? operator makes the *,+, or ? lazy. My question is how does it

4条回答
  •  时光取名叫无心
    2020-12-06 08:52

    Imagine you have the following text:

    BAAAAAAAAD
    

    The following regexs will return:

    /B(A+)/ => 'BAAAAAAAA'
    /B(A+?)/ => 'BA'
    /B(A*)/ => 'BAAAAAAAA'
    /B(A*?)/ => 'B'
    

    The addition of the "?" to the + and * operators make them "lazy" - i.e. they will match the absolute minimum required for the expression to be true. Whereas by default the * and + operators are "greedy" and try and match AS MUCH AS POSSIBLE for the expression to be true.

    Remember + means "one or more" so the minimum will be "one if possible, more if absolutely necessary" whereas the maximum will be "all if possible, one if absolutely necessary".

    And * means "zero or more" so the minimum will be "nothing if possible, more if absolutely necessary" whereas the maximum will be "all if possible, zero if absolutely necessary".

提交回复
热议问题