pattern.matcher() vs pattern.matches()

前端 未结 8 1888
时光说笑
时光说笑 2020-11-30 06:03

I am wondering why the results of the java regex pattern.matcher() and pattern.matches() differ when provided the same regular expression and same string

         


        
相关标签:
8条回答
  • 2020-11-30 06:24

    Pattern.matches is testing the whole String, in your case you should use:

     System.out.println(java.util.regex.Pattern.matches(".*\\+", str));
    

    Meaning any string and a + symbol

    0 讨论(0)
  • 2020-11-30 06:25

    From the Javadoc, see the if, and only if, the entire region section

       /**
         * Attempts to match the entire region against the pattern.
         *
         * <p> If the match succeeds then more information can be obtained via the
         * <tt>start</tt>, <tt>end</tt>, and <tt>group</tt> methods.  </p>
         *
         * @return  <tt>true</tt> if, and only if, <b>the entire region</b> sequence
         *          matches this matcher's pattern
         */
        public boolean matches() {
            return match(from, ENDANCHOR);
        }
    

    So if your String was just "+", you'd get a true result.

    0 讨论(0)
提交回复
热议问题