Java 17 Recipes


-14. Replacing All Text Matches


Download 3.2 Mb.
Pdf ko'rish
bet62/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   58   59   60   61   62   63   64   65   ...   245
Bog'liq
Java 17 Recipes

3-14. 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 
following example demonstrates this technique.
String str = "I love Java 8! It is my favorite language. Java 8
is the " + "8th version of this great programming language.";
Chapter 3 StringS


102
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("17"));
This example 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 Java 17! It is my favorite language. Java 17 is the 
17th version of this great programming language.
 How It Works
The replaceAll() method of the Matcher object makes it easy to find and replace a 
string or a portion of the string contained within a body of text. 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 Pattern.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-9]");
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 matched by the compiled pattern. In 
the solution to this recipe, the string "17" is passed to the replaceAll() method, so it 
replaces all the areas in the string that match the "[0-9]" pattern.

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   58   59   60   61   62   63   64   65   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling