The sample code:
String test = \"Z\";
Pattern pt = Pattern.compile(\"[0-9]*\");
Matcher mc = pt.matcher(test);
System.out.println(mc.find());
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!).
because Z
is not in the class [0-9]*
(This should matches only the digits between 0
to 9
check the demo regex), to match Z
it should be in the class [0-9Z]*
(demo regex)
Pattern pt = Pattern.compile("[0-9Z]*");