javaregex

Difference between Pattern class and Matcher class


What are the Pattern and Matcher classes in java and how do they differ?

My second question is, can you explain the following validation code clearly?

Pattern p = Pattern.compile("^[a-zA-Z][a-zA-Z\\s]+$");
Pattern pattern = Pattern.compile("\\d{10}");

Solution

  • Matcher --> A Matcher is created from a Pattern by invoking the Pattern's matcher method. The Matcher will match the given pattern (used to create it) against the String to be matched.

    Pattern --> A compiled representation of a regular expression. A regular expression, specified as a string, must first be compiled into an instance of this class.

    Pattern p = Pattern.compile("^[a-zA-Z][a-zA-Z\\s]+$"); 
    // creates a regex pattern that can match a character followed by one or more characters or space
    example : `ab` or `asa[space]` but not `a2` or `a` or `2`
    
    Pattern pattern = Pattern.compile("\\d{10}");
    // creates a regex pattern which can match exactly 10 digits
    example : 1234567890