Java:在基于正则表达式的HashMap键中搜索? [英] Java: Search in HashMap keys based on regex?
问题描述
我使用HashMap来构建同义词库来存储同义词。
我试图通过基于正则表达式的单词进行搜索:该方法必须将字符串作为参数并返回结果数组。这是我第一次刺穿它:
public ArrayList< String> searchDefinition(String regex){
ArrayList< String> results = new ArrayList< String>();
模式p = Pattern.compile(正则表达式);
Set< String> keys = thesaurus.keySet();
Iterator< String> ite = keys.iterator(); $(b)b
while(ite.hasNext()){
String candidate = ite.next();
Matcher m = p.matcher(候选人);
System.out.println(试图匹配:+ candidate +到+ regex);
if(m.matches()){
System.out.println(it matches);
results.add(候选人);
}
}
if(results.isEmpty()){
return null;
}
其他{
返回结果;
$ b现在,这不起作用,因为我期望或者我错误地使用了正则表达式)。如果我在hashmap中有下列键: cat,car,chopper
然后通过调用 searchDefinition(c)
或 searchDefinition(
$ b
- 如何按预期完成这项工作?
- 是否有比HashMap更好的数据结构来保持
图
类似于同义词库? (只有好奇心,因为这个任务我们被要求使用Java集合映射)。
- 我在上面的代码中做了什么不恰当的事情?
谢谢,
Dan
编辑:我已更正示例。即使我使用了正确的大小写,它也不起作用。
解决方案您需要指定大小写不敏感 Pattern.compile (c,
Pattern.CASE_INSENSITIVE )
。要查找带有 c
的单词,您需要使用 matcher.find()。 Matcher.matches()试图匹配整个字符串。
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;
}
}
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
then by calling searchDefinition("c")
or searchDefinition("c*")
I get null
.
- 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?
Thanks,
Dan
EDIT: I've corrected the example. It doesn't work even if I use the correct case.
解决方案 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键中搜索?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!