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
  • 1
    This doesn't cause the match to fail (see Carl's answer for that), but you don't have to escape the dot inside a character class. "[.\\d]" is enough (as a Java string). Commented Jul 29, 2010 at 16:04
  • Thanks, Tim. It works without the double escapes. When you say "a character class", is it the same as character set defined inside brackets? Commented Jul 29, 2010 at 16:27

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.