Pattern matching is to retrieve a string that matches a specified pattern. Java provides the Pattern class and Matcher class specifically used for pattern matching. These classes are in the java.util.regex package.
Next, let's talk about the steps of using the Pattern class and the Matcher class, assuming there is a string:
Stringinput=hello,goodmorning,thisisagoodidea;
We want to know where the input starts and ends where the string good appears.
First we need to create a pattern object and use the regular expression regex as a parameter to get an instance pattern of the Pattern class called pattern:
Patternpattern=Pattern.compile(regex);
For example:
Stringregex=good;pattern=Pattern.compile(regex);
Pattern objects are encapsulations of regular expressions. The Pattern class calls the class method compile(String regex) to return a pattern object, where the parameter regex is a regular expression, which is called the pattern used by the pattern object .
If the regular expression specified by the regex parameter is incorrect, the complie method will throw an exception PatternSyntaxException.
The Pattern class can also call the class method compile(String regex, int flags) to return a Pattern object. The parameter flags can take the following valid values:
Pattern.CASE_INSENSITIVEPattern.MULTILINEPattern.DOTALLPattern.UNICODE_CASEPattern.CANON_EQ
For example: flags takes the value Pattern.CASE_INSENSITIVE, and case will be ignored during pattern matching.