0

I'm trying to parse some text, but for some strange reason, Java regex doesn't work. For example, I've tried:

    Pattern p = Pattern.compile("[A-Z][0-9]*,[0-9]*");
    Matcher m = p.matcher("H3,4");

and it simply gives No match found exception, when I try to get the numbers m.group(1) and m.group(2). Am I missing something about how Java regex works?

1
  • See This question for code examples. Commented Nov 18, 2011 at 3:23

2 Answers 2

5

Yes.

  1. You must actually call matches() or find() on the matcher first.
  2. Your regex must actually contain capturing groups

Example:

Pattern p = Pattern.compile("[A-Z](\\d*),(\\d*)");
matcher m = p.matcher("H3,4");
if (m.matches()) {
    // use m.group(1), m.group(2) here
}
Sign up to request clarification or add additional context in comments.

Comments

0

You also need the parenthesis to specify what is part of each group. I changed the leading part to be anything that's not a digit, 0 or more times. What's in each group is 1 or more digits. So, not * but + instead.

Pattern p = Pattern.compile("[^0-9]*([0-9]+),([0-9]+)");
Matcher m = p.matcher("H3,4");
if (m.matches())
{
  String g1 = m.group(1);
  String g2 = m.group(2);
}

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.