Java: Search in HashMap keys based on regex?(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.
- 如何按预期完成这项工作?
- 是否有比 HashMap 更好的数据结构来保存同义词库所需的 graph?(只是好奇,至于这个作业我们被要求使用 Java Collection Map).
- 我在上面的代码中还有什么不恰当的地方吗?
- How do I make this work as expected?
- Is there a better data structure than HashMap to keep a graphlike needed by a thesaurus? (curiosity only, as for this assignment we're asked to use Java Collection Map).
- 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 键中搜索?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java:基于正则表达式在 HashMap 键中搜索?
 
				
         
 
            
        基础教程推荐
- Java Swing计时器未清除 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 从 python 访问 JVM 2022-01-01
 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
						 
						 
						 
						 
						 
				 
				 
				 
				