Java Reference
In-Depth Information
Note
Although regular expressions are used in many different languages today, the
expression syntax for each language varies. For complete information regarding regular
expression syntax, see the documentation online at
http://docs.oracle.com/
The easiest way to make use of regular expressions is to call the
matches()
method on the String object. Passing a regular expression to the
matches()
method
will yield a
boolean
result that indicates whether the String matches the given regu-
lar expression pattern or not. At this point, it is useful to know what a regular expres-
sion is and how it works.
A
regular expression
is a string pattern that is used to match against other strings in
order to determine its contents. Regular expressions can contain a number of different
patterns that enable them to be dynamic in that they can have the ability to match many
different strings that contain the same format. For instance, in the solution to this re-
cipe, the following code can match several different strings:
result = str.matches("I love Java [0-9]!");
The regular expression string in this example is
"I love Java [0-9]!"
, and
it contains the pattern
[0-9]
, which represents any number between 0 and 9. There-
fore, any string that reads
"I love Java"
followed by the numbers 0 through 9 and
then an exclamation point will match the regular expression string. To see a listing of
all the different patterns that can be used in a regular expression, see the online docu-
mentation available at the URL in the previous note.
A combination of
Pattern
and
Matcher
objects can also be used to achieve
similar results as the string
matcher()
method. The
Pattern
object can be used to
compile a string into a regular expression pattern. A compiled pattern can provide per-
formance gains to an application if the pattern is used multiple times. You can pass the
same string-based regular expressions to the
Pattern.compile()
method as you
would pass to the string
matches()
method. The result is a compiled
Pattern
ob-
ject that can be matched against a string for comparison. A
Matcher
object can be ob-
tained by calling the
Pattern
object's
matcher()
method against a given string.
Once a
Matcher
object is obtained, it can be used to match a given string against a
Pattern
using any of the following three methods, which each return a
boolean
value indicating a match. The following three lines of solution #2 could be used as an