tags:

views:

19

answers:

1

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.

+2  A: 

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() or Matcher.lookingAt(), or (if you want to be dumb and lazy like myself) simply tacking .* on the end of your pattern.

Carl Smotricz
Carl, thanks a lot for your answer. I append the .* at the end of regex, and it works. It confuses me because the split() method matches part of the input string. So, if I use the same regex in split() as used in matches(), it would give me an empty String[].Thanks again for your instant help.
Sapience