Java Reference
In-Depth Information
+ "8th version of this great programming
language.";
Pattern pattern = Pattern.compile("[0-9]");
Matcher matcher = pattern.matcher(str);
System.out.println("Original: " + str);
System.out.println(matcher.matches());
System.out.println("Replacement: "
+ matcher.replaceAll("7"));
This example will yield the following results:
Original: I love Java 8! It is my favorite language. Java
8 is the 8th version of this great programming language.
Replacement: I love version of this great programming
language.
How It Works
The
replaceAll()
method of the
Matcher
object makes it easy to find and re-
place a string or a portion of string that is contained within a body of text. In order to
use the
replaceAll()
method of the
Matcher
object, you must first compile a
Pattern
object by passing a regular expression string pattern to the
Pat-
tern.compile()
method. Use the resulting
Pattern
object to obtain a
Matcher
object by calling its
matcher()
method. The following lines of code show how this
is done:
Pattern pattern = Pattern.compile("[0-7]");
Matcher matcher = pattern.matcher(str);
Once you have obtained a
Matcher
object, call its
replaceAll()
method by
passing a string that you want to use to replace all the text that is matched by the com-
piled pattern. In the solution to this recipe, the string
"7"
is passed to the
re-
placeAll()
method, so it will replace all the areas in the string that match the
"[0-7]"
pattern.