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("[a-z]+", "XYZ");
System.out.println(result); // 输出 "123XYZ456"
替换字符串中的单个字符
使用 String.replace(char oldChar, char newChar) 替换单个字符。
String str = "apple";
String newStr = str.replace('a', 'A');
System.out.println(newStr); // 输出 "Apple"
使用 StringBuilder 进行高效替换
如果需要多次修改字符串,StringBuilder 更高效。
StringBuilder sb = new StringBuilder("Hello World");
sb.replace(6, 11, "Java");
System.out.println(sb.toString()); // 输出 "Hello Java"
替换文件中的内容
读取文件内容后替换字符串并写回文件。
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
String content = new String(Files.readAllBytes(Paths.get("file.txt")));
content = content.replace("old", "new");
Files.write(Paths.get("file.txt"), content.getBytes());
替换集合中的元素
使用 Collections.replaceAll() 替换列表中的元素。
import java.util.Collections;
import java.util.ArrayList;
import java.util.List;
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
Collections.replaceAll(list, "B", "C");
System.out.println(list); // 输出 [A, C]
替换 Map 中的键或值
直接通过 put 方法覆盖原有键值对。
import java.util.HashMap;
import java.util.Map;
Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key1", "newValue"); // 替换原有值
System.out.println(map.get("key1")); // 输出 "newValue"
使用正则表达式分组替换
通过正则表达式捕获组实现复杂替换逻辑。
String input = "John Doe (30)";
String output = input.replaceAll("(\\w+) (\\w+) \\((\\d+)\\)", "$2, $1 ($3)");
System.out.println(output); // 输出 "Doe, John (30)"
替换时忽略大小写
结合正则表达式标志 (?i) 实现不区分大小写的替换。

String text = "Hello HELLO hello";
String result = text.replaceAll("(?i)hello", "Hi");
System.out.println(result); // 输出 "Hi Hi Hi"






