看板java
标 题Re: [问题] 请问如何将正规表示法用在 HashMap.get()
发信站SayYA 资讯站 (Wed Dec 20 08:30:51 2006)
转信站ptt!ctu-reader!news.nctu!SayYa
※ 引述《[email protected] (小安)》之铭言:
> ※ 引述《Nt1 (用功点吧!)》之铭言:
> : 请问一下,若我有一个 HashMap,里面有:
> : key value
> : a
> : b
> : xax
> : ax
> : xa
> : 请问有什麽辨法可以将 key 中有包含 a 的(a, xax, ax, xa) 的value 都找出来呢?
> : 谢谢。
> 以 hash 来说,恐怕是没办法完成你要的功能
> 如果是我解这个问题,大概会用 26 个 ArrayList 分别代表 a~z
> 每加入一个字串,例如 hello
> 就将代表 h,e,l,o 的 ArrayList 加入 "hello"
> 但题目还有些细节不太确定,所以实际的写法还要再修改修改
这样也不错 :P
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
public class RegexUtil {
public static List<String> findSetWithRegex(Map<?, ?> m, String regex) {
List<String> l = new ArrayList<String>();
Set s = m.keySet();
Iterator it = s.iterator();
Pattern p = Pattern.compile(regex);
while (it.hasNext()) {
String k = it.next().toString();
System.out.println(k);
if (p.matcher(k).matches()) {
l.add(k);
}
}
return l;
}
public static void main(String[] args) {
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("a", "1");
hm.put("b", "2");
hm.put("xax", "3");
hm.put("ax", "4");
hm.put("xa", "5");
HashMap<Integer, String> hm2 = new HashMap<Integer, String>();
hm2.put(new Integer(6434), "1fd");
hm2.put(new Integer(3423), "dfa2");
hm2.put(new Integer(873), "d3sd");
List l = RegexUtil.findSetWithRegex(hm, "^a.*");
List l2 = RegexUtil.findSetWithRegex(hm2, ".*34.*");
System.out.println(l.size());
System.out.println(l2.size());
}
}
--
※ Origin: SayYA 资讯站 <bbs.sayya.org>
◆ From: 163.26.34.20