在此示例中,您将看到我们如何使用Java中的正则表达式类创建一个小的搜索和替换程序。下面的代码会将所有的棕色词替换为红色。
package org.nhooo.example.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";
        // 将给定的正则表达式编译为模式。
        Pattern pattern = Pattern.compile(find);
        // 创建一个匹配器,将匹配给定输入与
        // 模式。
        Matcher matcher = pattern.matcher(source);
        // 替换匹配输入序列的每个子序列
        // 具有给定替换字符串的模式。
        String output = matcher.replaceAll(replace);
        System.out.println("Source = " + source);
        System.out.println("Output = " + output);
    }
}代码段的结果是:
Source = The quick brown fox jumps over the brown lazy dog. Output = The quick red fox jumps over the red lazy dog.