java正则删除重复单词

import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        String str = "Is is the cost of of of of gasoline going up up up.";
        System.out.println(removeRepetWords(str, false));
        System.out.println(removeRepetWords(str, true));
    }

    static String removeRepetWords(String str, boolean ignoreCase) {
        if (str == null || str.isEmpty()) {
            return str;
        }
        String regex = "(\\w+)(\\s+\\1)+";
        if (ignoreCase) {
            return Pattern.compile(regex, Pattern.CASE_INSENSITIVE).matcher(str).replaceAll("$1");
        } else {
            return str.replaceAll(regex, "$1");
        }
    }
}

输入:Is is the cost of of of of gasoline going up up up.

输出:Is the cost of gasoline going up.

你可能感兴趣的:(java,单词去重)