Java Reference
In-Depth Information
[1] The .* means "zero or more characters," because . means "any character" and * means "zero or
more of the thing I follow," so together they mean "zero or more of any character."
13.3.2. Compiling and Matching with Regular Expressions
Evaluating a regular expression can be compute intensive, and in many
instances a single regular expression will be used repeatedly. This can
be addressed by compiling the regular expression once and using the
result. In addition, a single character sequence might be checked re-
peatedly against the same pattern to find multiple matches, which
can be done fastest by remembering some information about previous
matches. To address both these opportunities for optimization, the full
model of using a regular expression is this:
First you turn your regular expression string into a Pattern object
that is the compiled version of the pattern.
1.
Next you ask the Pattern object for a Matcher object that applies that
pattern to a particular CharSequence (such as a String or StringBuild-
er ).
2.
Finally you ask the Matcher to perform operations on the sequence
using the compiled pattern.
3.
Or, expressed in code:
Pattern pat = Pattern.compile(regularExpression);
Matcher matcher = pat.matcher(sequence);
boolean foundMatch = matcher.find();
If you are only using a pattern once, or are only matching each string
against that pattern once, you need not actually deal with the interme-
diate objects. As you will see, there are convenience methods on Pattern
for matching without a Matcher , and methods that create their own Pat-
tern and Matcher . These are easy to use, but inefficient if you are using
the same pattern multiple times, or matching against the same string
with the same pattern repeatedly.
 
 
Search WWH ::




Custom Search