我数据库中存入了如下数据作为字典库:
abc
abc123
aaaa现在我有一个字符串A: abc123sdfdfdf现在判断A中是否有字符串在字典库中存在Pattern p=Pattern.compile("(abc|aaaa|abc123)");
Matcher m=p.matcher(str);
while(m.find()){
  System.out.println(m.group(1));
}得到的结果是 abc而我希望得到abc123,即取最长的那个来作为匹配结果   请问要怎么实现??

解决方案 »

  1.   

    表达式中将abc123放在最前面就可以了。 Pattern p=Pattern.compile("(abc123|aaaa|abc)"); 
    Matcher m=p.matcher("abc123sdfdfdf"); 
    while(m.find()){ 
      System.out.println(m.group(1)); 
      

  2.   

    java.util.regex用的是传统的NFA正则表达式引擎,它的多选结构是按序排列的。所以只能把最长的多选分支放在前面,这样才能够匹配最长的字符串。