The code below demonstrates the use Matcher.appendReplacement()
and Matcher.appendTail()
methods to create a program to find and replace a sub string within a string.
Another solution that can be used to search and replace a string can be found on the following example: How do I create a string search and replace using regex?.
package org.kodejava.regex;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class AppendReplacementExample {
public static void main(String[] args) {
// Create a Pattern instance
Pattern pattern = Pattern.compile("[Pp]en");
// Create matcher object
String input = "Please use your Pen to answer the question, " +
"black pen is preferred.";
Matcher matcher = pattern.matcher(input);
StringBuilder builder = new StringBuilder();
// Find and replace the text that match the pattern
while (matcher.find()) {
matcher.appendReplacement(builder, "pencil");
}
// This method reads characters from the input sequence, starting
// at the beginning position, and appends them to the given string
// builder. It is intended to be invoked after one or more
// invocations of the appendReplacement method in order to copy
// the remainder of the input sequence.
matcher.appendTail(builder);
System.out.println("Input : " + input);
System.out.println("Output: " + builder);
}
}
Here is the result of the above code:
Input : Please use your Pen to answer the question, black pen is preferred.
Output: Please use your pencil to answer the question, black pencil is preferred.
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024