What is the difference between `Greedy` and `Reluctant` regular expression quantifiers?

后端 未结 5 1270
离开以前
离开以前 2020-11-29 07:41

From the Pattern javadocs:

Greedy quantifiers:
X?      X, once or not at all  
X*      X, zero or more times  
X+      X, one or more times  
X{n}    X, exactly n         


        
5条回答
  •  无人及你
    2020-11-29 07:59

    A greedy operator always try to "grab" as much of the input as possible, while a reluctant quantifier will match as little of the input as possible and still create a match.

    Example:

    "The red fox jumped over the red fence"
    /(.*)red/ => \1 = "The red fox jumped over the "
    /(.*?)red/ => \1 = "The "
    
    "aaa"
    /a?a*/ => \1 = "a", \2 = "aa"
    /a??a*/ => \1 = "", \2 = "aaa"
    
    "Mr. Doe, John"
    /^(?:Mrs?.)?.*\b(.*)$/ => \1 = "John"
    /^(?:Mrs?.)?.*?\b(.*)$/ => \1 = "Doe, John"
    

提交回复
热议问题