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 togroup(0), and group 0 denotes the entire pattern.From the documentation:
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+".