Java PatternSyntaxException
Pattern.compile throws PatternSyntaxException when a regular expression cannot be parsed. Validate a saved rule before applying it to product names.
A simple example
PatternSyntaxException
- Start with Pattern consisting of one open bracket
- Do this Compile the pattern
- Result Invalid pattern
Syntax
Pattern.compile(rule)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaValidate a saved product search
A store lets staff save a regular expression for product labels. A buyer leaves an opening bracket unfinished, so the search editor should highlight the invalid rule before it is saved.
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
class Main {
public static void main(String[] args) throws Exception {
try {
Pattern.compile("[sale");
} catch (PatternSyntaxException invalid) {
System.out.println("Fix the search pattern");
}
}
}
Fix the search pattern
The opening character class has no closing bracket. Compilation fails before any product label is searched.
Find a product label containing a bracket
A buyer pastes the literal shelf label [sale] into a product search. The app must look for those exact characters even though brackets have special meaning in a regular expression.
import java.util.regex.Pattern;
class Main {
public static void main(String[] args) throws Exception {
var literal = Pattern.compile(Pattern.quote("[sale]"));
System.out.println(literal.matcher("Mug [sale]").find());
}
}
true
Pattern.quote protects every character in the pasted literal.
Save a costume search
A costume librarian groups two rack prefixes in a character class. Compile the pattern before saving the search. An incomplete character class must go back to the editor.
Code and output in Java
import java.util.*;
import java.io.*;
import java.nio.file.*;
import java.util.concurrent.*;
class Main {
public static void main(String[] args) throws Exception {
try {
java.util.regex.Pattern.compile("[AB]");
System.out.println("Pattern accepted");
} catch (java.util.regex.PatternSyntaxException problem) {
System.out.println("Edit pattern");
}
}
}
Pattern accepted
What to watch for
If the form accepts literal product text, use Pattern.quote before putting it into a regex.