Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My Java regex isn't capturing the group

Tags:

java

regex

I'm trying to match the username with a regex. Please don't suggest a split.

USERNAME=geo

Here's my code:

    String input = "USERNAME=geo";
    Pattern pat = Pattern.compile("USERNAME=(\\w+)");
    Matcher mat = pat.matcher(input);
    if(mat.find()) {
        System.out.println(mat.group());
    }

why doesn't it find geo in the group? I noticed that if I use the .group(1), it finds the username. However the group method contains USERNAME=geo. Why?

like image 735
Geo Avatar asked Mar 23 '26 04:03

Geo


2 Answers

Because group() is equivalent to group(0), and group 0 denotes the entire pattern.

From the documentation:

public String group(int group)

Group zero denotes the entire pattern, so the expression m.group(0) is equivalent to m.group()

As you've found out, with your pattern, group(1) gives you what you want.

If you insist on using group(), you'd have to modify the pattern to something like "(?<=USERNAME=)\\w+".

like image 91
polygenelubricants Avatar answered Mar 24 '26 18:03

polygenelubricants


As Matcher.group() javadoc says, it "returns the input subsequence matched by the previous match", and the previous match in your case was "USERNAME=geo" since you've called find().

In contrast, the method group(int) returns specific group. Capturing groups are numbered by counting their opening parentheses from left to right, so the first group would match "geo" in your case.

like image 26
BorisOkunskiy Avatar answered Mar 24 '26 16:03

BorisOkunskiy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!