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.
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 complied 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:
actualString contains REGEX = true
actualString contains REGEX = false
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.