Java 使用正则表达式删除字符串中的重复(连续或非连续)字
如何在Java中使用正则表达式删除连续和非连续的重复/重复单词Java 使用正则表达式删除字符串中的重复(连续或非连续)字,java,regex,duplicates,Java,Regex,Duplicates,如何在Java中使用正则表达式删除连续和非连续的重复/重复单词 Hello to everyone hello in this world world \\ how do I convert this into Hello to everyone in this world \\into this 我确实找到了一个正则表达式,它可以找到不连续的重复单词: regex: (?s)(\b\w+\b)(?=.*\b\1\b) 那么,如何使用这个正则表达式来删除重复的单词并只保留重复单词的第一次
Hello to everyone hello in this world world \\ how do I convert this into
Hello to everyone in this world \\into this
我确实找到了一个正则表达式,它可以找到不连续的重复单词:
regex: (?s)(\b\w+\b)(?=.*\b\1\b)
那么,如何使用这个正则表达式来删除重复的单词并只保留重复单词的第一次出现?试试:
String text = "Hello to everyone hello in this world world \\ how do I convert this into";
Pattern p = Pattern.compile("(?i)(\\b\\w+\\b)(.*?) \\b\\1\\b");
Matcher m = p.matcher(text);
while (m.find()) {
text = m.replaceAll("$1$2");
m = p.matcher(text);
}
尝试:
这里是一种使用流的非正则表达式方法,假设单词由空格分隔
String original = "Hello to everyone hello in this world world";
Set<String> set = new HashSet<>();
String modified = Arrays.stream(original.split(" ")).filter(s -> set.add(s.toLowerCase())).collect(Collectors.joining(" "));
这里是一种使用流的非正则表达式方法,假设单词由空格分隔
String original = "Hello to everyone hello in this world world";
Set<String> set = new HashSet<>();
String modified = Arrays.stream(original.split(" ")).filter(s -> set.add(s.toLowerCase())).collect(Collectors.joining(" "));
这里是另一个备选方案,您可以使用两种不同的模式应用replaceAll两次。我可能遗漏了一些微妙之处,但这对提供的字符串有效
String str =
"how do do I remove how repeated words from this words sentence.";
String nonc = "(?i)(\\S+)(.*)(\\1(\\s|$))";
String conc = "(?i)(\\S+\\s)(\\1)";
str = str.replaceAll(nonc,"$1$2").replaceAll(conc, "$1");
System.out.println(str);
印刷品
how do I remove repeated words from this sentence.
这里是另一个备选方案,您可以使用两种不同的模式应用replaceAll两次。我可能遗漏了一些微妙之处,但这对提供的字符串有效
String str =
"how do do I remove how repeated words from this words sentence.";
String nonc = "(?i)(\\S+)(.*)(\\1(\\s|$))";
String conc = "(?i)(\\S+\\s)(\\1)";
str = str.replaceAll(nonc,"$1$2").replaceAll(conc, "$1");
System.out.println(str);
印刷品
how do I remove repeated words from this sentence.
或者只使用哈希集。或者只使用哈希集。@WJS,你是对的-它不能去除非连续词,我错过了。我已经更新了我的答案。@CodeHard它没有返回原始字符串;它摆脱了第二次世界大战。@Booboo-Thanx!!这帮了大忙@WJS,你是对的-它不能消除非连续词,我错过了。我已经更新了我的答案。@CodeHard它没有返回原始字符串;它摆脱了第二次世界大战。@Booboo-Thanx!!这帮了大忙