【发布时间】:2009-05-18 20:57:48
【问题描述】:
我正在使用 HashMap 构建同义词库来存储同义词。
我正在尝试基于正则表达式搜索单词:该方法必须将字符串作为参数并返回结果数组。这是我的第一次尝试:
public ArrayList<String> searchDefinition(String regex) {
ArrayList<String> results = new ArrayList<String>();
Pattern p = Pattern.compile(regex);
Set<String> keys = thesaurus.keySet();
Iterator<String> ite = keys.iterator();
while (ite.hasNext()) {
String candidate = ite.next();
Matcher m = p.matcher(candidate);
System.out.println("Attempting to match: " + candidate + " to " + regex);
if (m.matches()) {
System.out.println("it matches");
results.add(candidate);
}
}
if (results.isEmpty()) {
return null;
}
else {
return results;
}
}
现在,这不像我预期的那样工作(或者我可能错误地使用了正则表达式)。如果我在 hashmap 中有以下键:
cat, car, chopper
然后通过调用searchDefinition("c") 或searchDefinition("c*") 我得到null。
- 如何按预期进行这项工作?
- 是否有比 HashMap 更好的数据结构来保存同义词库所需的
graph? (只是好奇,至于这个作业我们被要求使用 Java Collection Map)。 - 我在上面的代码中还有什么不恰当的地方吗?
谢谢, 丹
编辑:我已经更正了这个例子。即使我使用正确的大小写它也不起作用。
【问题讨论】:
-
克林特有答案。但请注意,使用“c*”调用 find() 将匹配 any 条目——因为所有条目都有 0 个或多个 c。小心你的正则表达式。
-
特别是因为您将正则表达式直接传递给 Pattern 编译器。您可以轻松获得 PatternSyntaxException。
-
不是问题,但不要为空返回 null 并使用增强的 for 循环。