Why we should use whole string in Java regular expression

Java 8Object Oriented ProgrammingProgramming

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().


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());


'aa' Match:false
'aa' Match:true
Updated on 21-Jun-2020 14:14:42