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
graph
like 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 键中搜索?
基础教程推荐
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 降序排序:Java Map 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01