Java Reference
In-Depth Information
sions in which you will require a more flexible way of matching. Using this solution is
a three-step process:
1.
Compile a pattern into a Pattern object.
2.
Construct a Matcher object using the matcher() method on the
Pattern .
3.
Call the matches() method on the Matcher .
In the following example code, the Pattern and Matcher technique is demon-
strated:
String str = "I love Java 8!";
boolean result = false;
Pattern pattern = Pattern.compile("I love .*[ 0-9]!");
Matcher matcher = pattern.matcher(str);
result = matcher.matches();
System.out.println(result);
The previous example will yield a TRUE value just like its variant that was demon-
strated in solution #1.
How It Works
Regular expressions are a great way to find matches because they allow patterns to be
defined so that an application does not have to explicitly find an exact string match.
They can be very useful when you want to find matches against some text that a user
may be typing into your program. However, they could be overkill if you are trying to
match strings against a string constant you have defined in your program because the
String class provides many methods that could be used for such tasks. Nevertheless,
there will certainly come a time in almost every developer's life when regular expres-
sions can come in handy. They can be found in just about every programming language
used today. Java makes them easy to use and understand.
Search WWH ::




Custom Search