Search code examples
javaregexcapture-group

Capturing Groups REGEX Java


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.


Solution

  • You need to do find or matches :

    matcher.matches() or matcher.find()