java 如何替换
字符串替换
使用 String 类的 replace() 或 replaceAll() 方法。replace() 替换所有匹配的字符或字符串,replaceAll() 支持正则表达式。
String original = "Hello World";
String replaced = original.replace("World", "Java"); // "Hello Java"
String regexReplaced = original.replaceAll("[oO]", "X"); // "HellX WXrld"
文件内容替换
通过 BufferedReader 读取文件,逐行处理并写入新文件,最后替换原文件。

Path filePath = Paths.get("example.txt");
List<String> lines = Files.readAllLines(filePath, StandardCharsets.UTF_8);
List<String> modifiedLines = lines.stream()
.map(line -> line.replace("old", "new"))
.collect(Collectors.toList());
Files.write(filePath, modifiedLines, StandardCharsets.UTF_8);
集合元素替换
利用 List 的 replaceAll() 方法或 Stream API 批量修改元素。

List<String> list = Arrays.asList("a", "b", "c");
list.replaceAll(s -> s.equals("b") ? "new" : s); // ["a", "new", "c"]
正则表达式替换
结合 Pattern 和 Matcher 处理复杂替换逻辑。
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher("123abc456");
String result = matcher.replaceAll("X"); // "XabcX"
模板引擎替换
使用库如 StringTemplate 或 Velocity 动态替换模板中的占位符。
String template = "Hello ${name}!";
Map<String, String> data = Map.of("name", "Java");
String output = new StringTemplate(template).bind(data).render(); // "Hello Java!"






