我正在使用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;
}
}
Run Code Online (Sandbox Code Playgroud)
现在,这不会像我期望的那样工作(或者我可能错误地使用正则表达式).如果我在hashmap中有以下键:
cat, car, chopper
Run Code Online (Sandbox Code Playgroud)
然后通过电话searchDefinition("c")或searchDefinition("c*")我得到null.