How do I create a string search and replace using regex?

In this example you’ll see how we can create a small search and replace program using the regular expression classes in Java. The code below will replace all the brown words to red.

package org.kodejava.regex;

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class StringReplace {
    public static void main(String[] args) {
        String source = "The quick brown fox jumps over the brown lazy dog.";
        String find = "brown";
        String replace = "red";

        // Compiles the given regular expression into a pattern.
        Pattern pattern = Pattern.compile(find);

        // Creates a matcher that will match the given input against the
        // pattern.
        Matcher matcher = pattern.matcher(source);

        // Replaces every subsequence of the input sequence that matches
        // the pattern with the given replacement string.
        String output = matcher.replaceAll(replace);

        System.out.println("Source = " + source);
        System.out.println("Output = " + output);
    }
}

The result of the code snippet is:

Source = The quick brown fox jumps over the brown lazy dog.
Output = The quick red fox jumps over the red lazy dog.

How do I replace characters in string?

package org.kodejava.lang;

public class StringReplace {
    public static void main(String[] args) {
        String text = "The quick brown fox jumps over the lazy dog";
        System.out.println("Before: " + text);

        // The replace method replace all occurrences of character
        // 'o' with 'u' and returns a new string object.
        text = text.replace('o', 'u');
        System.out.println("After : " + text);
    }
}

The result of the code snippet:

Before: The quick brown fox jumps over the lazy dog
After : The quick bruwn fux jumps uver the lazy dug