如何用替换/正则表达式替换字符串中的两个字符?



我想修改字符串中的两个字符,例如将每个'i'更改为'e',并将每个'e'更改为'i',因此像"This is a test"这样的文本将变为"Thes es a tist"

我提出了一个有效的解决方案,但它既无聊又不优雅:

String input = "This is a test";
char a = 'i';
char b = 'e';
char[] chars = input.toCharArray();
for(int i = 0; i < chars.length; i++) {
if(chars[i] == a) {
chars[i] = b;
}else if(chars[i] == b) {
chars[i] = a;
}
}
input = new String(chars);

如何使用正则表达式实现这一点?

从 Java 9 开始,我们可以使用Matcher#replaceAll(Function<MatchResult,String>).因此,您可以创建正则表达式,它将搜索ie,当它找到它时,让函数根据找到的值选择替换(例如从地图中(

演示

Map<String, String> replacements = Map.ofEntries(
Map.entry("i", "e"), 
Map.entry("e", "i")
);
String replaced = Pattern.compile("[ie]")
.matcher(yourString)
.replaceAll((match) -> replacements.get(match.group()));

但老实说,您的解决方案看起来还不错,特别是如果它用于搜索单个字符。

一个不如Pschemo的优雅的解决方案,但自Java 8以来可以使用:

static String swap(String source, String a, String b) {
// TODO null/empty checks and length checks on a/b
return Arrays
// streams single characters as strings
.stream(source.split(""))
// maps characters to their replacement if applicable
.map(s -> {
if (s.equals(a)) {
return b;
}
else if (s.equals(b)) {
return a;
}
else {
return s;
}
})
// rejoins as single string
.collect(Collectors.joining());
}

"This is a test"调用时,它返回:

Thes es a tist

注意

正如其他人提到的,您的解决方案与单个字符一样很好。

最新更新