本文目录导读:

我来详细说明Java中使用正则表达式替换字符的各种案例和方法。
基础替换方法
String.replaceAll() 方法
public class RegexReplaceExample {
public static void main(String[] args) {
String text = "Hello World 123 Java 456";
// 替换数字为"#"
String result1 = text.replaceAll("\\d+", "#");
System.out.println(result1); // Hello World # Java #
// 替换空格为-
String result2 = text.replaceAll("\\s+", "-");
System.out.println(result2); // Hello-World-123-Java-456
}
}
常用替换案例
案例1:删除所有数字
String text = "abc123def456ghi";
String result = text.replaceAll("\\d+", "");
System.out.println(result); // abcdefghi
案例2:替换邮箱域名
String email = "user@old-domain.com";
String result = email.replaceAll("@.*\\.com$", "@new-domain.com");
System.out.println(result); // user@new-domain.com
案例3:手机号中间四位隐藏
String phone = "13812345678";
String result = phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
System.out.println(result); // 138****5678
使用分组捕获
案例1:日期格式转换(YYYY-MM-DD 转 MM/DD/YYYY)
String date = "2024-03-15";
String result = date.replaceAll("(\\d{4})-(\\d{2})-(\\d{2})", "$2/$3/$1");
System.out.println(result); // 03/15/2024
案例2:提取并重组URL参数
String url = "https://example.com/page?id=123&name=test";
String result = url.replaceAll("id=(\\d+)", "user=$1");
System.out.println(result); // https://example.com/page?user=123&name=test
使用Matcher类进行复杂替换
案例1:条件替换
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ComplexReplace {
public static void main(String[] args) {
String text = "价格: $100, 五折后价格: $50";
Pattern pattern = Pattern.compile("\\$\\d+");
Matcher matcher = pattern.matcher(text);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
String number = matcher.group().replace("$", "");
int price = Integer.parseInt(number);
// 如果价格大于80,加折扣标记
if (price > 80) {
matcher.appendReplacement(sb, "💲" + (price / 2) + "(已打折)");
} else {
matcher.appendReplacement(sb, matcher.group());
}
}
matcher.appendTail(sb);
System.out.println(sb.toString());
// 价格: 💲50(已打折), 五折后价格: $50
}
}
实用替换模式
去除HTML标签
String html = "<p>Hello <b>World</b></p>";
String clean = html.replaceAll("<[^>]+>", "");
System.out.println(clean); // Hello World
驼峰命名转下划线
String camelCase = "userNameAndPassword";
String underscore = camelCase.replaceAll("([A-Z])", "_$1").toLowerCase();
System.out.println(underscore); // user_name_and_password
格式化手机号
String phone = "13812345678";
String formatted = phone.replaceAll("(\\d{3})(\\d{4})(\\d{4})", "$1-$2-$3");
System.out.println(formatted); // 138-1234-5678
性能优化建议
// 对于多次使用的正则,预编译Pattern
private static final Pattern NUMBER_PATTERN = Pattern.compile("\\d+");
private static final Pattern SPACE_PATTERN = Pattern.compile("\\s+");
public String optimizeReplace(String text) {
text = NUMBER_PATTERN.matcher(text).replaceAll("*");
text = SPACE_PATTERN.matcher(text).replaceAll("-");
return text;
}
特殊情况处理
替换时包含特殊字符
// 如果替换字符串中包含特殊字符,需要转义
String text = "Hello $100";
String replacement = Matcher.quoteReplacement("$150"); // $符号需要转义
String result = text.replaceAll("\\$100", replacement);
System.out.println(result); // Hello $150
不区分大小写替换
String text = "Hello HELLO hello";
String result = text.replaceAll("(?i)hello", "Hi");
System.out.println(result); // Hi Hi Hi
完整示例代码
public class RegexReplaceDemo {
public static void main(String[] args) {
// 1. 基础替换
String text1 = "Hello World 123 Java 456";
System.out.println(text1.replaceAll("\\d+", "#"));
// 2. 分组捕获
String phone = "13812345678";
System.out.println(phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
// 3. 去除空格
String text2 = " Hello World ";
System.out.println(text2.replaceAll("^\\s+|\\s+$", "")); // 去除首尾空格
// 4. 下划线转驼峰
String underscore = "user_name";
System.out.println(underscore.replaceAll("_(\\w)",
m -> m.group(1).toUpperCase()));
// 5. 重复单词去重
String repeat = "hello hello world";
System.out.println(repeat.replaceAll("\\b(\\w+)\\s+\\1\\b", "$1"));
}
}
这些案例涵盖了Java正则替换的主要应用场景,你可以根据实际需求选择合适的替换方式。