The pattern class of the java.regex package is a compiled representation of a regular expression.
The compile() method of this class accepts a string value representing a 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[] ) { //Reading string value Scanner sc = new Scanner(System.in); System.out.println("Enter input string"); String input = sc.nextLine(); //Regular expression to find digits String regex = "(\\d)"; //Compiling the regular expression Pattern pattern = Pattern.compile(regex); //Printing the regular expression System.out.println("Compiled regular expression: "+pattern.toString()); //Retrieving the matcher object Matcher matcher = pattern.matcher(input); //verifying whether match occurred if(matcher.find()) { System.out.println("Given String contains digits"); } else { System.out.println("Given String does not contain digits"); } } }
Output
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 flags, where each flag specifies an optional condition, for example, CASE_INSENSITIVE ignores the case while 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[] ) { //Compiling the regular expression Pattern pattern = Pattern.compile("[t]", Pattern.CASE_INSENSITIVE); //Retrieving the matcher object Matcher matcher = pattern.matcher("Tutorialspoint"); int count = 0; while(matcher.find()) { count++; } System.out.println("Number of matches: "+count); } }
Output
Enter input string Tutorialspoint Number of matches: 3