1

I am trying to use Pattern and Matcher to determine if a given string has a space between 2 digits. For example "5 1" should come back as true, "51" should come back as false. At first I was using string.replaceAll with the regex and it worked great, but moveing to Pattern I can't seem to get it to work.

    String findDigit = "5      1/3";
    String regex = "(\\d) +(\\d)";
    findDigit = findDigit.replaceAll(regex, "$1 $2");

    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(findDigit);
    System.out.println(m.matches());
    System.out.println(m.hitEnd()); 

I first started with this. The replaceAll works without a hitch and removes the extra spaces, but the m.matches and the m.hitEnd both return false. Then I thought I might be doing something wrong so I simplified the case to just

    String findDigit = "5";
    String regex = "\\d";
    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(findDigit);
    System.out.println(m.matches());
    System.out.println(m.hitEnd()); 

and matches comes back true (obviously) but when I change it to this

    String findDigit = "5 3";
    String regex = "\\d";
    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(findDigit);
    System.out.println(m.matches());
    System.out.println(m.hitEnd()); 

comes back both false. So I guess my main question is how to I determine that there is ANY digit in my string first and then more specifically, how do I deteremine if there is a digit space digit in my string. I thought that was the hitEnd, but I guess I am mistaken. Thanks in advance.

2
  • Why the -1 so quickly with no explanation as to why? Commented May 15, 2014 at 16:03
  • Well thank you to whoever voted me back up, and I realize now that I was being stupid... m.find(). smacks head on desk Commented May 15, 2014 at 16:06

2 Answers 2

2

If you're looking for a match with multiple spaces but would like to preserve the formatting of the output you could use groups and back-references.

For instance:

String input = "blah 5             6/7";
Pattern p = Pattern.compile("(\\d)\\s+(\\d)");
Matcher m = p.matcher(input);
while (m.find()) {
    System.out.printf("Whole match: %s\n\tFirst digit: %s\n\tSecond digit: %s\n", m.group(), m.group(1), m.group(2));
}

Output

Whole match: 5             6
    First digit: 5
    Second digit: 6
Sign up to request clarification or add additional context in comments.

1 Comment

This actually greatly helped me answer another question I was having so thank you!
0

The answer is of course m.find() sorry for being stupid this morning. Thanks to all who even looked at this :)

Comments

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.