0

I'd like to capture the groups in my regular expression but it seems that I haven't written it as it should be. Consider the following lines:

String input = "username=johndoe";
Pattern pattern = Pattern.compile("(\\w+)=(\\w+)");
Matcher matcher = pattern.matcher(input);

When I try to capture the group one and two I've got an IllegalStateExcpetion. I really don't know what's wrong with my regex, and I also tried several different ways of writing it =/.

Thanks in advance for your help.

victorcmg
  • 3
  • 1

2 Answers2

2

You are getting IllegalStateExcpetion because you forgot to call either:

matcher.matches()

OR

matcher.find()

You can access captured groups only after calls to either of the 2 methods shown above.

anubhava
  • 761,203
  • 64
  • 569
  • 643
0

You need to do find or matches :

matcher.matches() or matcher.find()

Rakesh KR
  • 6,357
  • 5
  • 40
  • 55