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.util.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 prefered.";
        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.

        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 prefered.
Output: Please use your pencil to answer the question, black pencil is prefered.
Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.
Wayan Saryada

Leave a Reply