java如何快速替换
替换字符串中的内容
使用 String.replace() 方法可以快速替换字符串中的特定字符或子串。该方法接受两个参数:要替换的目标和替换后的新内容。例如:
String original = "Hello World";
String replaced = original.replace("World", "Java");
System.out.println(replaced); // 输出 "Hello Java"
使用正则表达式替换
String.replaceAll() 方法支持正则表达式,适合复杂替换场景。例如替换所有数字为 #:

String text = "123abc456";
String result = text.replaceAll("\\d", "#");
System.out.println(result); // 输出 "###abc###"
替换文件中的内容
通过 Files 类和 BufferedReader/BufferedWriter 实现文件内容替换:
Path path = Paths.get("example.txt");
List<String> lines = Files.readAllLines(path);
List<String> modifiedLines = lines.stream()
.map(line -> line.replace("old", "new"))
.collect(Collectors.toList());
Files.write(path, modifiedLines);
集合元素的批量替换
使用 Collections.replaceAll() 方法替换列表中所有匹配项:

List<String> list = new ArrayList<>(Arrays.asList("A", "B", "A"));
Collections.replaceAll(list, "A", "Z");
System.out.println(list); // 输出 [Z, B, Z]
使用第三方库进行高级替换
Apache Commons Lang 的 StringUtils 提供更多替换选项:
String output = StringUtils.replaceEach(input,
new String[]{"foo", "bar"},
new String[]{"new1", "new2"});
模式匹配替换
Java 9+ 的 Matcher.replaceAll() 支持函数式替换:
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher("a1b22c");
String result = matcher.replaceAll(match -> "[" + match.group() + "]");
// 输出 "a[1]b[22]c"






