Java正则-String.matches的坑 版本 java8

今天在处理一个正则匹配时,使用原来的方式写好正则表达式,在正则表达式在线测试网站测试正常;

放在测试用例中始终都时false;

String agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36";

System.out.println("agent:"+agent.matches("/Mozilla|AppleWebKit|Chrome/i"));

网上一通查找,发现此文章 说正则表达式会在前后添加 ^$ 进行匹配,修改测试代码片段测试基本符合 

String agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36";

System.out.println("agent:"+agent.matches("/Mozilla|AppleWebKit|Chrome/i"));  //false     System.out.println("agent2:"+Pattern.compile("Mozilla|AppleWebKit|Chrome").matcher(agent).matches());//false
System.out.println("agent2:"+agent.matches(".*[Mozilla|AppleWebKit|Chrome].*")); //true

随手打开Java8 的Pattern 源码,发现在javadoc中已经说明了匹配的方式

//Pattern.matches() 
public static boolean matches(String regex, CharSequence input) {
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(input);
        return m.matches();
    }




Matcher.matches()

/**
     * Attempts to match the entire region against the pattern.
     *
     * 

If the match succeeds then more information can be obtained via the * start, end, and group methods.

* * @return true if, and only if, the entire region sequence * matches this matcher's pattern */ public boolean matches() { return match(from, ENDANCHOR); }

仅在整个输入串匹配正则表达式的时候返回 true; 

你可能感兴趣的:(java,8)