NoBugs
NoBugs

Reputation: 9496

Java regex doesn't find numbers

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?

Upvotes: 0

Views: 470

Answers (2)

Mike
Mike

Reputation: 2464

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);
}

Upvotes: 0

C. K. Young
C. K. Young

Reputation: 222983

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
}

Upvotes: 5

Related Questions