【发布时间】:2012-02-27 04:04:45
【问题描述】:
我认为这是在字符串中查找重复单词的答案。但是当我使用它时,它认为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;
}
【问题讨论】:
-
我认为应该是:\b(\w+)\b\s+\1\b 否则它会认为 'ice' 和 'icecream' 是重复的。
-
rubular.com/r/Qr3twc03RR(我又调了一下,好像是字边界问题... \b(\w+)\b\s+\b\1\b )
-
在末尾添加另一个单词边界对我来说非常有效。但即使没有这个,你的正则表达式也不应该匹配
This is。你的问题可能出在其他地方,虽然我无法想象那会在哪里。 -
虽然你有你的答案,但你可能会考虑改变你的方法。一个基本的分词器和一个类似 Set 的结构更容易理解并且可能更有效。
-
正则表达式现在是正确的,但是您需要再次将所有这些反斜杠加倍。事实上,代码甚至无法编译。此外,您正在做大量不必要的工作。整个方法可以写成
return input.replaceAll("(?i)\\b(\\w+)\\s+\\1\\b", "$1");