正则表达式与目标不匹配

时间:2018-05-10 09:05:32

标签: java regex

让我们说我们有一个字符串列表如下 - admin,sam1,sam2,max,maximus

Then in search box if I give 
     *a*m* should return admin
     *sam* should return sam1,sam2
     m* should return max,maximus
     max* should return max,maximus

我的代码如下(示例代码,不查看列表): -

   private static final String REGEX = ".*max*.";
   private static final String INPUT = "maximus";
   private static Pattern pattern;
   private static Matcher matcher;

   public static void main( String args[] ) {
      System.out.println("matches(): "+matcher(REGEX,INPUT));
   }

   private static boolean matcher(String filterCriteria,String parentString) 
  {
       Pattern pattern = Pattern.compile(filterCriteria);
       Matcher matcher = pattern.matcher(parentString);
       return matcher.matches();       
   }

少数,输出错误,但必须是真的:

  1. private static final String REGEX = ".*ad*.";
     private static final String INPUT = "admin";

  2. private static final String REGEX = ".*max*.";
     private static final String INPUT = "max11";

  3. private static final String REGEX = ".*sa*.";
     private static final String INPUT = "sam1";  

1 个答案:

答案 0 :(得分:1)

正如staszko032

中的评论中已经提到的那样,你的正则表达式不正确
.*ad*.

这个正则表达式意味着:

  • .*零个或多个字符
  • literal a
  • d*零个或多个d字符
  • .任何角色

相反它应该是:

.*ad.*

意思是:

  • .*零个或多个字符
  • literal ad
  • .*零个或多个字符