杰瑞科技汇

Java字符串替换正则表达式如何高效使用?

Java 字符串替换与正则表达式

在 Java 中,可以使用正则表达式进行字符串替换操作,主要有以下几种方法:

Java字符串替换正则表达式如何高效使用?-图1
(图片来源网络,侵删)

String.replaceAll()

public String replaceAll(String regex, String replacement)

使用正则表达式替换所有匹配的子字符串。

String str = "Hello 123 World 456";
String result = str.replaceAll("\\d+", "数字");
System.out.println(result); // 输出: Hello 数字 World 数字

String.replaceFirst()

public String replaceFirst(String regex, String replacement)

只替换第一个匹配的子字符串。

String str = "Hello 123 World 456";
String result = str.replaceFirst("\\d+", "数字");
System.out.println(result); // 输出: Hello 数字 World 456

Pattern 和 Matcher 类

对于更复杂的替换操作,可以使用 PatternMatcher 类:

import java.util.regex.*;
String input = "Hello 123 World 456";
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(input);
StringBuffer result = new StringBuffer();
while (matcher.find()) {
    matcher.appendReplacement(result, "数字");
}
matcher.appendTail(result);
System.out.println(result.toString()); // 输出: Hello 数字 World 数字

替换中的反向引用

在替换字符串中可以使用 $n 引用捕获组:

Java字符串替换正则表达式如何高效使用?-图2
(图片来源网络,侵删)
String str = "John Smith, Jane Doe";
String result = str.replaceAll("(\\w+) (\\w+)", "$2, $1");
System.out.println(result); // 输出: Smith, John Doe, Jane

特殊替换字符

替换字符串中可以使用以下特殊字符:

  • $0 - 整个匹配的字符串
  • $n - 第n个捕获组
  • $& - 整个匹配的字符串(同$0)
  • $` - 匹配前的字符串
  • - 匹配后的字符串
  • - 字符串"$"
String str = "abc123def";
String result = str.replaceAll("\\d+", "[$&]");
System.out.println(result); // 输出: abc[123]def

注意事项

  1. 正则表达式中的反斜杠需要双写(如 \d 要写成 \\d
  2. 替换字符串中的 字符需要转义为
  3. 对于简单的字符串替换(非正则),应使用 String.replace() 方法,它更高效且不需要转义特殊字符
// 简单字符串替换(非正则)
String str = "Hello World";
String result = str.replace("World", "Java");
System.out.println(result); // 输出: Hello Java
分享:
扫描分享到社交APP
上一篇
下一篇