Java Reference
In-Depth Information
System
.
exit
(
1
);
}
Pattern patt
=
Pattern
.
compile
(
args
[
0
]);
Matcher matcher
=
patt
.
matcher
(
""
);
String line
=
null
null
;
while
while
((
line
=
is
.
readLine
()) !=
null
null
) {
matcher
.
reset
(
line
);
iif
(
matcher
.
find
()) {
System
.
out
.
println
(
"MATCH: "
+
line
);
}
}
}
}
Controlling Case in Regular Expressions
Problem
You want to find text regardless of case.
Solution
Compile the
Pattern
passing in the
flags
argument
Pattern.CASE_INSENSITIVE
to indic-
ate that matching should be case-independent (“fold” or ignore differences in case). If your
code might run in different locales (see
Chapter 15
) then you should add
Pat-
tern.UNICODE_CASE
. Without these flags, the default is normal, case-sensitive matching be-
havior. This flag (and others) are passed to the
Pattern.compile()
method, as in:
// CaseMatch.java
Pattern reCaseInsens = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE |
Pattern.UNICODE_CASE);
reCaseInsens.matches(input); // will match case-insensitively
This flag must be passed when you create the
Pattern
; because
Pattern
objects are immut-
able, they cannot be changed once constructed.
The full source code for this example is online as
CaseMatch.java
.