How do I find and replace string?

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.
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.