Why we should use whole string in Java regular expression


In Java regex matches() matches the input string against the whole string as it add a ^ and $ at the end of the input string.so it will not match the substring. So for matching substring, you should use find().

Example

import java.util.regex.*;
class PatternMatchingExample {
   public static void main(String args[]) {
      String content = "aabbcc";
      String string = "aa";
      Pattern p = Pattern.compile(string);
      Matcher m = p.matcher(content);
      System.out.println(" 'aa' Match:"+ m.matches());
      System.out.println(" 'aa' Match:"+ m.find());
   }
}

Output

'aa' Match:false
'aa' Match:true

Updated on: 21-Jun-2020

747 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements