Syntax error Why we should use whole string in Java regular expression

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: 2020-06-21T14:14:42+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements