What exactly does .*? do in regex? ".*?([a

This question already has an answer here:

  • Greedy vs. Reluctant vs. Possessive Quantifiers 7 answers

  • The ? here acts as a 'modifier' if I can call it like that and makes .* match the least possible match (termed 'lazy') until the next match in the pattern.

    In fall/2005 , the first .*? will match up to the first match in ([am/]*) , which is just before f . Hence, .*? matches 0 characters so that ([am/]*) will match fall/ and since ([am/]*) cannot match anymore, the next part of the pattern .* matches what's left in the string, meaning 2005 .

    In contrast to .*([am/]*).* , you would have .* match as much as possible first (meaning the whole string) and try to go back to make the other terms match. Except that the problem is with the other quantifiers being able to match 0 characters as well, so that .* alone will match the whole string (termed 'greedy').


    Maybe a different example will help.

    .*ab
    

    In:

    aaababaaabab
    

    Here, .* will match as much characters as possible and then try to match ab . Thus, .* will match aaababaaab and the remainder will be matched by ab .

    .*?ab
    

    In:

    aaababaaabab
    

    Here, .*? will match as little as possible until it can match ab in that regex. The first occurrence of ab is here:

    aaababaaabab
      ^^
    

    And so, .*? matches aa while ab will match ab .


    In regex:

    ? : Occurs no or one times, ? is short for {0,1}

    * ? : ? after a quantifier makes it a reluctant quantifier, it tries to find the smallest match.


    Suppose if you have a string input like this

    this is stackoverflow
    

    and you use regex

    .*
    

    so output will be

    this is stackoverflow
    

    but if you use regex

    .*?
    

    your out put will be

    this
    

    So from the above example it is clear that if you use .* it will give you whole string. to prevent this if you want only first cherector before space you should use .*?

    For more practical knowledge you can check http://regexpal.com/

    链接地址: http://www.djcxy.com/p/76894.html

    上一篇: java正则表达式X的例子 ,X +和X?

    下一篇: 究竟是什么。*? 用正则表达式吗? “。*?([一个