Regular Expression fails to matches() pattern with asterisk sign

后端 未结 2 1798
情话喂你
情话喂你 2021-01-29 10:09

The sample code:

    String test = \"Z\";
    Pattern pt = Pattern.compile(\"[0-9]*\");
    Matcher mc = pt.matcher(test);
    System.out.println(mc.find());
            


        
2条回答
  •  后悔当初
    2021-01-29 10:44

    The pattern [0-9]* says "matches 0 or more times of 0-9". If it sees a digit it will add that to the match. If it doesn't see a digit it still adds a 0 length string to the match. It does not mean match any string with 0 or more digits (because every string has 0 or more digits, which makes this pointless) So in your string Z, there are two zero-length matches: one at the start of the string and one at the end of the string, both of which has 0 digits.

    This means that find will return true twice and matches will return false because the whole string is not a match (remember there are wo matches!).

提交回复
热议问题