java 如何替换
字符串替换
在Java中,替换字符串内容可以使用String类的replace、replaceAll和replaceFirst方法。这些方法适用于不同的替换需求。
replace方法用于替换所有匹配的字符或字符串:
String original = "Hello World";
String replaced = original.replace("Hello", "Hi");
System.out.println(replaced); // 输出: Hi World
replaceAll方法使用正则表达式匹配并替换所有符合条件的内容:
String original = "123abc456";
String replaced = original.replaceAll("[a-z]+", "XYZ");
System.out.println(replaced); // 输出: 123XYZ456
replaceFirst方法仅替换第一个匹配项:

String original = "abc123abc456";
String replaced = original.replaceFirst("abc", "XYZ");
System.out.println(replaced); // 输出: XYZ123abc456
正则表达式替换
当需要更复杂的匹配规则时,可以结合Pattern和Matcher类进行正则表达式替换:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
String input = "The price is $100 and $200";
Pattern pattern = Pattern.compile("\\$\\d+");
Matcher matcher = pattern.matcher(input);
String output = matcher.replaceAll("XXX");
System.out.println(output); // 输出: The price is XXX and XXX
文件内容替换
替换文件中的内容通常需要读取文件、替换内容后重新写入:
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
String filePath = "example.txt";
String content = new String(Files.readAllBytes(Paths.get(filePath)));
String newContent = content.replace("old", "new");
Files.write(Paths.get(filePath), newContent.getBytes());
集合元素替换
在集合中替换元素可以使用Collections类的replaceAll方法:

import java.util.Collections;
import java.util.ArrayList;
import java.util.List;
List<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("apple");
Collections.replaceAll(list, "apple", "orange");
System.out.println(list); // 输出: [orange, banana, orange]
正则表达式分组替换
利用正则表达式的分组功能可以实现更灵活的替换:
String input = "John Doe, Jane Smith";
String output = input.replaceAll("(\\w+) (\\w+)", "$2, $1");
System.out.println(output); // 输出: Doe, John, Smith, Jane
字符串构建器替换
对于大量字符串操作,使用StringBuilder的replace方法更高效:
StringBuilder sb = new StringBuilder("Hello World");
sb.replace(6, 11, "Java");
System.out.println(sb.toString()); // 输出: Hello Java
正则表达式特殊字符处理
替换包含正则表达式特殊字符时需要转义:
String input = "1 + 2 = 3";
String output = input.replaceAll("\\+", "plus");
System.out.println(output); // 输出: 1 plus 2 = 3






