简体   繁体   English

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

[英]How to replace two characters in a String with replace/regex?

I want to modify two characters in the string, for example change each 'i' into 'e' , and each 'e' into 'i' so text like "This is a test" will become "Thes es a tist" . 我想修改字符串中的两个字符,例如将每个'i'更改为'e' ,并将每个'e'更改为'i' ,这样"This is a test"这样的文本将变为"Thes es a tist"

I've made a solution that works, but it is boring and inelegant: 我已经提出了一个可行的解决方案,但是它很无聊而且很优雅:

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);

How can this be accomplished with regex? 如何用正则表达式来完成?

Since Java 9 we can use Matcher#replaceAll(Function<MatchResult,String>) . 从Java 9开始,我们可以使用Matcher#replaceAll(Function<MatchResult,String>) So you can create regex which will search for either i or e , and when it finds it let function pick replacement based on found value (like from map) 因此,您可以创建将搜索ie正则表达式,并在找到时让函数根据找到的值选择替换(例如从地图中获取)

Demo 演示版

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()));

But to be honest your solution doesn't look bad, especially if it is used for searching for single characters. 但老实说,您的解决方案看起来并不坏,特别是如果该解决方案用于搜索单个字符。

A less elegant solution than Pschemo's but usable since Java 8: 比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());
}

Invoked on "This is a test" , it returns: "This is a test"上调用,它返回:

Thes es a tist

Note 注意

As mentioned by others, your solution is fine as is for single characters. 正如其他人所提到的,您的解决方案和单个字符一样不错。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM