如何用replace/regex替换String中的两个字符?

Muh*_*jer 0 java regex string

我想修改两个字符字符串中,例如在改变'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);
Run Code Online (Sandbox Code Playgroud)

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

Psh*_*emo 5

从Java 9开始我们就可以使用了Matcher#replaceAll(Function<MatchResult,String>).所以你可以创建正在搜索任何一个i或者的正则表达式e,当它找到它时,让函数根据找到的值选择替换(比如map)

演示

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()));
Run Code Online (Sandbox Code Playgroud)

但说实话,你的解决方案看起来并不坏,特别是如果它用于搜索单个字符.