相关疑难解决方法(0)

Java:基于正则表达式在HashMap密钥中搜索?

我正在使用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.

  1. 如何按预期工作?
  2. 是否有比HashMap更好的数据结构来保持 …

java regex hashmap

14
推荐指数
2
解决办法
3万
查看次数

标签 统计

hashmap ×1

java ×1

regex ×1