Java SE API
Pattern.compile()
Compile a reusable pattern; invalid syntax throws PatternSyntaxException. Java SE API; example uses Java 21-compatible syntax.
Formal Syntax & Structure
java syntaxjava
static Pattern compile(String regex)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| regex | String | Regular expression |
Return Value
Pattern
Compile a reusable pattern; invalid syntax throws PatternSyntaxException.
Working Example
Example Snippetjava
import java.util.*;import java.util.regex.*;import java.nio.*;import java.nio.charset.*;import java.io.*;import javax.xml.XMLConstants;import javax.xml.parsers.*;import org.xml.sax.*;import org.xml.sax.helpers.DefaultHandler;import org.w3c.dom.*;public class Main { public static void main(String[] args) throws Exception { var p = Pattern.compile("[A-Z]{2}-[0-9]{3}"); System.out.println(p.matcher("AB-123").matches()); System.out.println(p.matcher("AB-123 extra").matches()); System.out.println(p.matcher("AB-123 extra").lookingAt()); System.out.println(p.matcher("item AB-123").find()); }}