Pattern compile(String) method in Java with Examples

The compile(String) method of the Pattern class in Java is used to create a pattern from the regular expression passed as parameter to method. Whenever you need to match a text against a regular expression pattern more than one time, create a Pattern instance using the Pattern.compile() method.
Syntax:Â
public static Pattern compile(String regex)
Parameters: This method accepts one single parameter regex which represents the given regular expression compiled into a pattern.
Return Value: This method returns the pattern compiled from the regex passed to the method as a parameter.
Exception: This method throws following exception:Â Â
- PatternSyntaxException: This exception is thrown if the expression’s syntax is invalid.
Below programs illustrate the compile(String) method:Â
Program 1:Â Â
Java
// Java program to demonstrate// Pattern.compile() methodÂ
import java.util.regex.*;Â
public class GFG {    public static void main(String[] args)    {        // create a REGEX String        String REGEX = ".*www.*";Â
        // create the string        // in which you want to search        String actualString            = "www.zambiatek.com";Â
        // compile the regex to create pattern        // using compile() method        Pattern pattern = Pattern.compile(REGEX);Â
        // get a matcher object from pattern        Matcher matcher = pattern.matcher(actualString);Â
        // check whether Regex string is        // found in actualString or not        boolean matches = matcher.matches();Â
        System.out.println("actualString "                           + "contains REGEX = "                           + matches);    }} |
actualString contains REGEX = true
Â
Program 2:Â
Java
// Java program to demonstrate// Pattern.compile methodÂ
import java.util.regex.*;Â
public class GFG {    public static void main(String[] args)    {        // create a REGEX String        String REGEX = "brave";Â
        // create the string        // in which you want to search        String actualString            = "Cat is cute";Â
        // compile the regex to create pattern        // using compile() method        Pattern pattern = Pattern.compile(REGEX);Â
        // check whether Regex string is        // found in actualString or not        boolean matches = pattern                              .matcher(actualString)                              .matches();Â
        System.out.println("actualString "                           + "contains REGEX = "                           + matches);    }} |
actualString contains REGEX = false
Â
Reference: https://docs.oracle.com/javase/10/docs/api/java/util/regex/Pattern.html#compile(java.lang.String)



