我在stackoverflow上看到了一个用来查找字符串中重复单词的答案。但是当我使用它时,它认为This
和is
是相同的,并删除了is
。
正则表达式
"\\b(\\w+)\\b\\s+\\1"
任何想法为什么会发生这种情况?以下是我用于去重的代码。
public static String RemoveDuplicateWords(String input)
{
String originalText = input;
String output = "";
Pattern p = Pattern.compile("\b(\w+)\b\s+\b\1\b", Pattern.MULTILINE+Pattern.CASE_INSENSITIVE);
//Pattern p = Pattern.compile("\\b(\\w+)\\b\\s+\\1", Pattern.MULTILINE+Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(input);
if (!m.find())
output = "No duplicates found, no changes made to data";
else
{
while (m.find())
{
if (output == "")
output = input.replaceFirst(m.group(), m.group(1));
else
output = output.replaceAll(m.group(), m.group(1));
}
input = output;
m = p.matcher(input);
while (m.find())
{
output = "";
if (output == "")
output = input.replaceAll(m.group(), m.group(1));
else
output = output.replaceAll(m.group(), m.group(1));
}
}
return output;
}
return input.replaceAll("(?i)\\b(\\w+)\\s+\\1\\b", "$1");
。 - Alan Moore