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

Java: Search in HashMap keys based on regex?(Java:基于正则表达式在 HashMap 键中搜索?)
本文介绍了Java:基于正则表达式在 HashMap 键中搜索?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 HashMap 构建同义词库来存储同义词.

I'm building a thesaurus using a HashMap to store the synonyms.

我正在尝试基于正则表达式搜索单词:该方法必须将字符串作为参数并返回结果数组.这是我的第一次尝试:

I'm trying to search through the words based on a regular expression: the method will have to take a string as parameter and return an array of results. Here's my first stab at it:

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 中有以下键:

Now, this does not work as I would expect (or maybe I'm using regular expressions incorrectly). If I have the following keys in the hashmap:

cat, car, chopper

然后通过调用 searchDefinition("c")searchDefinition("c*") 我得到 null.

then by calling searchDefinition("c") or searchDefinition("c*") I get null.

  1. 如何按预期完成这项工作?
  2. 是否有比 HashMap 更好的数据结构来保存同义词库所需的 graph?(只是好奇,至于这个作业我们被要求使用 Java Collection Map).
  3. 我在上面的代码中还有什么不恰当的地方吗?
  1. How do I make this work as expected?
  2. Is there a better data structure than HashMap to keep a graph like needed by a thesaurus? (curiosity only, as for this assignment we're asked to use Java Collection Map).
  3. Anything else I'm doing innapropriately in the code above?

谢谢,丹

我已经更正了这个例子.即使我使用正确的大小写它也不起作用.

I've corrected the example. It doesn't work even if I use the correct case.

推荐答案

需要指定不区分大小写 Pattern.compile( "c",Pattern.CASE_INSENSITIVE ).要查找其中包含 c 的单词,您需要使用 matcher.find().Matcher.matches() 尝试匹配整个字符串.

You need to specify case insensitivity Pattern.compile( "c",Pattern.CASE_INSENSITIVE ). To find a word with a c in it you need to use matcher.find(). Matcher.matches() tries to match the whole string.

这篇关于Java:基于正则表达式在 HashMap 键中搜索?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How can create a producer using Spring Cloud Kafka Stream 3.1(如何使用Spring Cloud Kafka Stream 3.1创建制片人)
Insert a position in a linked list Java(在链接列表中插入位置Java)
Did I write this constructor properly?(我是否正确地编写了这个构造函数?)
Head value set to null but tail value still gets displayed(Head值设置为空,但仍显示Tail值)
printing nodes from a singly-linked list(打印单链接列表中的节点)
Control namespace prefixes in web services?(控制Web服务中的命名空间前缀?)