I’m working on a regex that could match the leading digits and . in a String. But it seems just not working correctly. The regex I’m using is
"^[\\.\\d]+"
Below is my code:
public void testMiscellaneous() throws Exception {
System.out.println("~~~~~~~~~~~~~~~~~~~testMiscellaneous~~~~~~~~~~~~~~~~~~~~");
String s1 = ".123 *[DP7_Dog]";
String s2 = ".123";
String s3 = "1.12.3";
String s4 = "a1.12.3";
final String numberRegex = "^[\\.\\d]+";
System.out.println(s1.matches(numberRegex));
System.out.println(s2.matches(numberRegex));
System.out.println(s3.matches(numberRegex));
System.out.println(s4.matches(numberRegex));
}
The outputs are
false
true
true
false
However, I would expect true, true, true, false. There must be something wrong with the regex, but I can’t find it. Can anybody help? Thanks.
The problem is that
matches()insists on matching your entire input String, as if there was a^at the beginning of your regexp and$at the end.You may be better off using
Matcher.find()orMatcher.lookingAt(), or (if you want to be dumb and lazy like myself) simply tacking.*on the end of your pattern.