Lazy
Lazy

Reputation: 1837

Java pattern capture word(s)

I'm trying to capture word or words from a string like this:

input: "aa bb"
pattern: "(.*) bb"
expected group: "aa"

input: "aa yy bb xx"
pattern: "(.*) bb (.*)"
expected groups: "aa yy, xx"

But in my attempts it always captures whole string. Where is my mistake?

String patternString = "(.*) bb";
Log("patternString: " + patternString);

Pattern p = Pattern.compile(patternString);
Matcher m = p.matcher("aa bb");

while(m.find()) {
    Log("group: " + m.group());
    //Log: group: aa bb
}

Upvotes: 1

Views: 74

Answers (1)

M A
M A

Reputation: 72844

You want to get the first group not the entire match. You should use m.group(1) for this, instead of m.group() which returns the entire match.

See the documentation of Matcher for the available API. Use Matcher#groupCount() to get the number of groups in the last match.

Upvotes: 4

Related Questions