Why does this pattern matching code not work?

60 views Asked by At

I'm trying to do some pattern matching in Java:

Pattern p = Pattern.compile("(\\d+) (\\.+)");
Matcher m = p.matcher("5 soy milk");
String qty = m.group(1);
String name = m.group(2);

I want to end up with one string that contains "5" and one string that contains "soy milk". However, this pattern matching code gives me an IllegalStateException.

2

There are 2 answers

0
Greg Kopff On BEST ANSWER

You have to call matches() before you attempt to get the groups.

http://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html#matches()

public boolean matches()

Attempts to match the entire region against the pattern. If the match succeeds then more information can be obtained via the start, end, and group methods.

Try this:

Pattern p = Pattern.compile("(\\d+) (\\.+)");
Matcher m = p.matcher("5 soy milk");

if (m.matches())
{
  String qty = m.group(1);
  String name = m.group(2);
}
0
fge On

This is because you don't initiate your Matcher. You should p.matcher(...).matches() (or .find(), or .lookingAt(), depending on the desired behaviour -- real regex matching is done with .find()).

And check the result of .matches() since in your case it returns false: \.+ ("\\.+" in a Java string) will try and match a dot one or more times; you should use .+ (".+" in a Java string) to match "any character, one or more times".