Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Java Pattern.quote: match a supplied token literally

Last updated: 5 Oct 20264 min read
tutorial
IntermediateBy AITrove Editorial

Pattern.quote turns supplied text into a literal regex operand so punctuation in that text cannot change the match rule.

Separate the rule from the token

A routing rule may search for a product code supplied by another system. A code containing a dot is data, not an instruction to match any character. Concatenate the quoted token into the fixed expression; compile the result once when the rule is reused.

The program finds SKU.47 but rejects SKUX47. Without quoting, the dot matches the X as well. matches versus find covers the separate question of whether the whole input or a substring must match.

Keep a size boundary

Literal quoting prevents regex syntax injection. It does not cap input length or make an unrelated surrounding expression safe from expensive backtracking. Bound externally supplied tokens before constructing a pattern.

Working program

Java
import java.util.regex.Pattern;

public class ProductTokenSearch {
    public static void main(String[] args) {
        String productCode = "SKU.47";
        Pattern route = Pattern.compile("(?:^|,)" + Pattern.quote(productCode) + "(?:,|$)");
        System.out.println(route.matcher("SKU.47,SKU.48").find());
        System.out.println(route.matcher("SKUX47,SKU.48").find());
    }
}

Output

Output
true
false

Cost and ownership

Pattern compilation allocates matcher machinery once; each matcher owns mutable scan state and its cost depends on input size and the surrounding expression. The literal token cannot add regex operators, but an unbounded input still consumes scan time and memory.

Common Mistakes

  • Do not concatenate untrusted text directly into regex syntax.
  • Do not share one Matcher across threads; share the compiled Pattern instead.
  • Do not treat quoting as an input-length limit.

Read next

Java strings and content equality, regex matches find, regex quote replacement, Java String.split: preserve empty trailing fields in a record.

java
regex
regex-quote-user-input
Storage details