Difference between regex quantifiers plus and star

前端 未结 5 1763
轮回少年
轮回少年 2020-11-27 08:37

I try to extract the error number from strings like \"Wrong parameters - Error 1356\":

 Pattern p = Pattern.compile(\"(\\\\d*)\");
 Matcher m =          


        
相关标签:
5条回答
  • 2020-11-27 09:06

    With the pattern /d+ at least one digit will need to be reached, and then the match will return all subsequent characters until a non-digit character is reached.

    /d* will match all the empty strings (zero or more), as well at the match. The .Net Regex parser will return all these empty string groups in its set of matches.

    0 讨论(0)
  • 2020-11-27 09:12
    \d* Eat as many digits as possible (but none if necessary)
    

    \d* means it matches a digit zero or more times. In your input, it matches the least possible one (ie, zero times of the digit). So it prints none.

    \d+
    

    It matches a digit one or more times. So it should find and match a digit or a digit followed by more digits.

    0 讨论(0)
  • 2020-11-27 09:14

    The * quantifier matches zero or more occurences.

    In practice, this means that

    \d*

    will match every possible input, including the empty string. So your regex matches at the start of the input string and returns the empty string.

    0 讨论(0)
  • 2020-11-27 09:14

    but none if necessary means that it will not break the regex pattern if there is no match. So \d* means it will match zero or more occurrences of digits.

    For eg.

    \d*[a-z]*
    

    will match

    abcdef
    

    but \d+[a-z]*

    will not match

    abcdef
    

    because \d+ implies that at least one digit is required.

    0 讨论(0)
  • 2020-11-27 09:15

    Simply:

    \d* implies zero or more times

    \d+ means one or more times

    0 讨论(0)
提交回复
热议问题