Library contents

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

  1. Start with Pattern consisting of one open bracket
  2. Do this Compile the pattern
  3. Result Invalid pattern
The bracket begins a character class that never closes. Compiling detects the problem before a search.

Syntax

Java syntax
Pattern.compile(rule)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Validate 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.

ResultFix the search pattern
Main.java
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");
        }
    }
}
Output
Fix the search pattern

The opening character class has no closing bracket. Compilation fails before any product label is searched.

Advertisements

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.

Resulttrue
Main.java
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());
    }
}
Output
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.

Given[AB]
Worked resultPattern accepted
Code and output in Java
Java source
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");
        }
    }
}
Output
Pattern accepted

What to watch for

If the form accepts literal product text, use Pattern.quote before putting it into a regex.

Documentation for PatternSyntaxException