Open In App

Pattern compile(String,int) method in Java with Examples

The compile(String, int) method of the Pattern class used to create a pattern from the regular expression with the help of flags where both expression and flags are passed as parameters to the method. The Pattern class contains a list of flags (int constants) that can be helpful to make the Pattern matching behave in certain ways. For example, The flag name CASE_INSENSITIVE is used to ignore the case of the text at the time of matching.
Syntax:  

public static Pattern compile(String regex, int flags)

Parameters: This method accepts two parameters:  



Return Value: This method returns the pattern compiled from passed regex and flags.
Exception: This method throws following exceptions:  

Below programs illustrate the compile(String, int) method:
Program 1: 






// 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 = "(.*)(for)(.*)?";
 
        // create the string
        // in which you want to search
        String actualString
            = "code of Machine";
 
        // compile the regex to create pattern
        // using compile() method
        Pattern pattern = Pattern.compile(REGEX,
                           Pattern.CASE_INSENSITIVE);
 
        // check whether Regex string is
        // found in actualString or not
        boolean matches = pattern
                              .matcher(actualString)
                              .matches();
 
        System.out.println("actualString "
                           + "contains REGEX = "
                           + matches);
    }
}

Output: 
actualString contains REGEX = false

 

Time Complexity : O(N)

Space Complexity : O(1)

Program 2: 
 




// 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 = ".*org.*";
 
        // create the string
        // in which you want to search
        String actualString
            = "geeksforgeeks.org";
 
        // compile the regex to create pattern
        // using compile() method
        Pattern pattern = Pattern.compile(REGEX,
                             Pattern.CASE_INSENSITIVE);
 
        // check whether Regex string is
        // found in actualString or not
        boolean matches = pattern
                              .matcher(actualString)
                              .matches();
 
        System.out.println("actualString "
                           + "contains REGEX = "
                           + matches);
    }
}

Output: 
actualString contains REGEX = true

 

Time Complexity : O(N)

Space Complexity : O(1)

References: 
https://docs.oracle.com/javase/10/docs/api/java/util/regex/Pattern.html#compile(java.lang.String, int)


Article Tags :