Java Reference
In-Depth Information
groupCount()
Returns the number of parenthesized capture groups, if any; returns 0 if no groups were
used.
group(int i)
Returns the characters matched by group
i
of the current match, if
i
is greater than or
equal to zero and less than or equal to the return value of
groupCount()
. Group 0 is the
entire match, so
group(0)
(or just
group()
) returns the entire portion of the input that
matched.
The notion of parentheses or “capture groups” is central to regex processing. Regexes may
be nested to any level of complexity. The
group(int)
method lets you retrieve the charac-
ters that matched a given parenthesis group. If you haven't used any explicit parens, you can
just treat whatever matched as “level zero.”
Example 4-2
shows part of
REMatch.java
.
Example 4-2. Part of REMatch.java
public
public class
class
REmatch
REmatch
{
public
public static
static
void
void
main
(
String
[]
argv
) {
String patt
=
"Q[^u]\\d+\\."
;
Pattern r
=
Pattern
.
compile
(
patt
);
String line
=
"Order QT300. Now!"
;
Matcher m
=
r
.
matcher
(
line
);
iif
(
m
.
find
()) {
System
.
out
.
println
(
patt
+
" matches \""
+
m
.
group
(
0
) +
"\" in \""
+
line
+
"\""
);
}
else
else
{
System
.
out
.
println
(
"NO MATCH"
);
}
}
}
When run, this prints:
Q[\^u]\d+\. matches "QT300." in "Order QT300. Now!"