我想写一个正则表达式来替换重复的字符串,而不考虑大小写



例如

String str="**Hello bye bye given given world world**"

应该返回

"**Hello bye given world**".

您可以使用空格拆分字符串,并通过仅将非重复值存储在列表中来将字符串与以前的字符串匹配

代码将如下所示。

import java.util.ArrayList;
import java.util.List;
public class Test2 {
    private static final String SPACE = " ";
    public static void main(String[] args) {
        System.out.println(replaceDuplicateString("**Hello Bye bye given given world world**"));
    }
    public static String replaceDuplicateString(String input) {
        List<String> addedList = new ArrayList<>();
        StringBuilder output = new StringBuilder();
        for (String str: input.split(SPACE)) {
            if (!addedList.contains(str.toUpperCase())) {
                output.append(str);
                output.append(' ');
                addedList.add(str.toUpperCase());
            }
        }
        return output.toString().trim();
    }
}

这将打印

Hello bye given world

如果您将输入更改为

**Hello bye bye given given world world**

输出将是

**Hello bye given world world**

因为,world不是world**的重复.

最新更新