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.example.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);
        StringBuffer sb = new StringBuffer();

        // Find and replace the text that match the pattern
        while (matcher.find()) {
            matcher.appendReplacement(sb, "pencil");
        }

        // This method reads characters from the input sequence, starting
        // at the append position, and appends them to the given string
        // buffer. 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(sb);

        System.out.println("Input : " + input);
        System.out.println("Output: " + sb.toString());
    }
}

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 Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you 🥳

Leave a Reply

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