java实现hash查找,Java:在基于正则表达式的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 searchDefinition(String regex) {

ArrayList results = new ArrayList();

Pattern p = Pattern.compile(regex);

Set keys = thesaurus.keySet();

Iterator 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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值