在Java开发中,正则表达式是处理字符串匹配和替换的强大工具。本文将详细介绍Java中使用正则表达式进行字符串替换的各种方法。
String类提供了最简单的正则表达式替换方法:
String str = "Hello 123 World 456";
String result = str.replaceAll("\\d+", "***");
// 输出:Hello *** World ***
对于更复杂的替换需求,可以使用Pattern和Matcher类:
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher("Hello 123 World 456");
String result = matcher.replaceAll("***");
需要更灵活控制替换过程时:
Pattern p = Pattern.compile("cat");
Matcher m = p.matcher("one cat two cats in the yard");
StringBuffer sb = new StringBuffer();
while(m.find()) {
m.appendReplacement(sb, "dog");
}
m.appendTail(sb);
// 结果:one dog two dogs in the yard
可以使用$n引用捕获组:
String str = "John Smith";
String result = str.replaceAll("(\\w+) (\\w+)", "$2, $1");
// 输出:Smith, John
掌握这些Java正则表达式替换方法,可以大大提高字符串处理的效率和灵活性。