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?
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 tom.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+".
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With