English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

compile() method with examples in Java

java.regexThe package's pattern class is the compiled representation of a regular expression.

This classcompile()The method accepts a string value representing the regular expression and returns a Pattern object.

Example

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CompileExample {
   public static void main(String args[]) {
      //Read string value
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input string");
      String input = sc.nextLine();
      //Regular expression to find numbers
      String regex = "(\\d)";
      //Compile regular expression
      Pattern pattern = Pattern.compile(regex);
      //Print the regular expression
      System.out.println("Compiled regular expression: "+pattern.toString());
      //Search matcher object
      Matcher matcher = pattern.matcher(input);
      //Verify whether a match occurs
      if(matcher.find()) {
         System.out.println("Given String contains digits");
      } else {
         System.out.println("Given String does not contain digits");
      }
   }
}

Output result

Enter input string
hello my id is 1120KKA
Compiled regular expression: (\d)
Given String contains digits

Another variant of this method accepts an integer value representing the flags, where each flag specifies an optional condition, such as CASE_INSENSITIVE to ignore case when compiling the regular expression.

Example

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CompileExample {
   public static void main(String args[]) {
      //Compile regular expression
      Pattern pattern = Pattern.compile("[t]", Pattern.CASE_INSENSITIVE);
      //Search matcher object
      Matcher matcher = pattern.matcher("w"3codebox);
      int count = 0;
      while(matcher.find()) {
         count++;
      }
      System.out.println("Number of matches: ",+count);
   }
}

Output result

Enter input string
w3codebox
Number of matches: 3