Java Reference
In-Depth Information
alternate solution to using the Pattern.matches() method, minus the reusability
of the compile pattern:
Pattern pattern = Pattern.compile("I love .*[ 0-9]!");
Matcher matcher = pattern.matcher(str);
result = matcher.matches();
The Matcher matches() method attempts to match the entire input
string with the pattern.
The Matcher lookingAt() method attempts to match the input
string to the pattern starting at the beginning.
The Matcher find() method scans the input sequence looking for
the next matching sequence in the string.
In the solution to this recipe, the matches() method is called against the
Matcher object in order to attempt to match the entire string. In any event, regular
expressions can be very useful for matching strings against patterns. The technique
used for working with the regular expressions can vary in different situations, using
whichever method works best for the situation.
3-9. Replacing All Text Matches
Problem
You have searched a body of text for a particular sequence of characters, and you are
interested in replacing all matches with another string value.
Solution
Use a regular expression pattern to obtain a Matcher object; then use the Matcher
object's replaceAll() method to replace all matches with another string value. The
example that follows demonstrates this technique:
String str = "I love Java 8! It is my favorite
language. Java 8 is the "
Search WWH ::




Custom Search