Java Pattern compile() Method
Example
Create a pattern that ignores upper and lower case, and search for it in a text:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("w3schools", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher("Visit W3Schools!");
System.out.println(matcher.find());
}
}
Definition and Usage
The compile() method turns a regular expression (a pattern that describes the text you search for) into a Pattern object.
It is a static method, so you call it on the class: Pattern.compile("w3schools"). Add flags (options) as the second argument to change how the search works. In the example, Pattern.CASE_INSENSITIVE makes the search ignore upper and lower case.
Tip: You can use a Pattern many times. Compile it once, and then call its matcher() method for each text you want to search.
Syntax
One of the following:
public static Pattern compile(String regex)
public static Pattern compile(String regex, int flags)
Parameter Values
| Parameter | Description |
|---|---|
| regex | Required. The regular expression, as a String. |
| flags | Optional. One or more flags that change how the search works, like Pattern.CASE_INSENSITIVE. To use more than one flag, join them with |, for example Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE. |
Technical Details
| Returns: | A new Pattern object. |
|---|---|
| Throws: | PatternSyntaxException - if the regular expression is not valid, for example "[abc", where the ] is missing. |
Related Pages
❮ RegEx Methods