Java Reference
In-Depth Information
Of course, you can perform regex matching in other ways, such as using the convenience
methods in
Pattern
or even in
java.lang.String
. For example:
public
public class
class
StringConvenience
StringConvenience
{
public
public static
static
void
void
main
(
String
[]
argv
) {
String pattern
=
".*Q[^u]\\d+\\..*"
;
String line
=
"Order QT300. Now!"
;
iif
(
line
.
matches
(
pattern
)) {
System
.
out
.
println
(
line
+
" matches \""
+
pattern
+
"\""
);
}
else
else
{
System
.
out
.
println
(
"NO MATCH"
);
}
}
}
But the three-step list just described is the “standard” pattern for matching. You'd likely use
the
String
convenience routine in a program that only used the regex once; if the regex were
being used more than once, it is worth taking the time to “compile” it because the compiled
version runs faster.
In addition, the
Matcher
has several finder methods, which provide more flexibility than the
String
convenience routine
match()
. The
Matcher
methods are:
match()
Useda to compare the entire string against the pattern; this is the same as the routine in
java.lang.String
. Because it matches the entire
String
, I had to put
.*
before and
after the pattern.
lookingAt()
Used to match the pattern only at the beginning of the string.
find()
Used to match the pattern in the string (not necessarily at the first character of the string),
starting at the beginning of the string or, if the method was previously called and suc-
ceeded, at the first character not matched by the previous match.