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

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
raja
Published on 01-Oct-2018 08:09:33
Advertisements