Groovy regex: escape special characters

How to escape regex special characters in Groovy: slashy strings, doubled backslashes, Pattern.quote, replacement strings, and when a plain-text method is safer.

Groovy regular expressions run on the Java regex engine, so the characters that need escaping are the same as in Java. What differs is how many backslashes you type, and that depends on the kind of Groovy string that holds the pattern. This review covers what escaping changes, which approach suits which job, and where an escaped pattern can break once it leaves the file it was written in.

Short answer: which approach to use

Use a slashy string such as /\d+.\d{2}/ for patterns you write by hand. It needs one backslash per regex escape, which keeps patterns readable. Use Pattern.quote when the text to match comes from a variable, user input or a file, because it makes the whole value literal without you listing metacharacters. The tradeoff is portability: a pattern escaped for one Groovy string form, or quoted with Pattern.quote, often stops working if you paste it into a different string form or another regex engine. If you only need to find or replace a fixed piece of text, skip regex and use a plain string method instead.

What escaping actually changes

Escaping changes the stored characters of your pattern. It is not a visual or font effect. Adding a backslash before a metacharacter tells the regex engine to match that character literally instead of using its special meaning. A second, separate layer comes from the Groovy string literal itself, which may consume backslashes or treat a dollar sign as interpolation before the regex engine sees the pattern.

  • Characters with special meaning outside a character class in Java and Groovy regex:
  • . (any character)
  • ^ and $ (anchors)
  • + ? and { } (quantifiers)
  • ( ) (groups)
  • [ ] (character classes)
  • | (alternation)
  • \ (the escape character itself)

Inside square brackets the rules narrow. Most of the characters above are literal there, but ] closes the class, \ still escapes, ^ negates when it comes first, and - forms a range when it sits between two characters. Escaping a character that did not need it, such as . inside [ ], is harmless in Java regex, so over-escaping is a readability cost rather than a correctness bug in most cases.

How each Groovy string form handles backslashes

String form | Regex for a literal "4.99" | What you must watch
Slashy /.../ | /4.99/ | Backslashes are not doubled; a forward slash must be written /; $ followed by an identifier or { is interpolated
Single-quoted '...' | '4\.99' | Every regex backslash is doubled; no interpolation
Double-quoted "..." | "4\.99" | Backslashes are doubled and $ triggers GString interpolation
Dollar-slashy $/.../$ | $/4.99/$ | Backslashes are not doubled; a literal $ is written $$ and a literal slash can be written $/
Pattern.quote(value) | Pattern.quote('4.99') | No manual escaping; the result is wrapped in \Q...\E
import java.util.regex.Pattern

def text = 'Total: 4.99 (USD)'

// Slashy string: one backslash per regex escape
assert text =~ /4\.99 \(USD\)/

// Single-quoted string: each regex backslash is doubled
assert text =~ '4\\.99 \\(USD\\)'

// Pattern.quote: the whole value is matched literally
def needle = '4.99 (USD)'
assert text =~ Pattern.quote(needle)

Slashy strings have a few edge cases. Two slashes with nothing between them start a line comment, not an empty pattern. A backslash right before the closing slash escapes the delimiter, so a pattern cannot end with a lone backslash. If a slashy pattern contains a dollar sign followed by letters, Groovy may try to interpolate it. In that case, a single-quoted string or a dollar-slashy string avoids the ambiguity.

Escaping arbitrary input with Pattern.quote

Pattern.quote returns the input wrapped between \Q and \E, which the Java regex engine reads as a literal span. For example, quoting 1+1=2 produces \Q1+1=2\E. It also handles input that itself contains \E, so you do not need to pre-clean the value. This is the safest choice for values you did not write yourself, because a hand-maintained list of metacharacters is easy to get wrong. The cost is that the quoted output is harder to read in logs or debuggers. Passing the Pattern.LITERAL flag to Pattern.compile gives the same literal behavior for a whole pattern.

Replacement strings need their own escaping

In replaceAll and replaceFirst, the replacement argument is not a regex, but it has its own special characters: $ refers to a captured group and \ escapes. A replacement such as '$5' with no fifth group throws an exception rather than inserting the text. Matcher.quoteReplacement makes the replacement literal. In Groovy, also keep $1-style group references in single quotes, because a double-quoted string would attempt interpolation. Groovy's closure form of replaceAll is another option: the closure's return value is used as the replacement.

import java.util.regex.Matcher

def out = 'cost: X'.replaceAll('X', Matcher.quoteReplacement('$5'))
assert out == 'cost: $5'

// Group reference: single quotes keep $1 away from interpolation
assert 'a-b'.replaceAll(/(\w)-(\w)/, '$2-$1') == 'b-a'

When plain text is the better choice

Some methods take a regex even though their names do not say so, and that is where unescaped special characters cause the most surprises. String.split takes a regex, so splitting on "." matches every character and returns an empty array. Groovy's tokenize treats its argument as a set of literal delimiter characters, and String.replace and contains work on literal text. If you have no need for anchors, groups or quantifiers, these literal methods remove the escaping problem entirely and are easier to read.

assert 'a.b.c'.split('.').length == 0           // regex: dot matches everything
assert 'a.b.c'.split(/\./) == ['a', 'b', 'c'] as String[]
assert 'a.b.c'.tokenize('.') == ['a', 'b', 'c']  // literal delimiter
assert 'a.b.c'.replace('.', '/') == 'a/b/c'      // literal replace

Will an escaped pattern survive copying and sharing?

  • Between Groovy string forms: a slashy pattern pasted into single or double quotes loses half its escaping, and the reverse adds extra backslashes.
  • Into Java: Java string literals require doubled backslashes, so a slashy pattern needs converting before it compiles correctly.
  • Into other regex engines: \Q...\E is a Java-family feature; JavaScript regex, for example, does not support it, so Pattern.quote output is not portable there.
  • Through config and data formats: putting a pattern in JSON, YAML or a properties file adds that format's own escaping rules on top of the regex escaping.
  • Through rich-text tools: word processors and some chat or documentation editors can replace straight quotes with curly ones, which breaks Groovy string delimiters.

Heavily escaped patterns are hard for people to read, and that affects maintenance more than correctness. Splitting a long pattern into named parts, or using the (?x) comments flag to add whitespace and comments, keeps it reviewable. No evidence was available on how specific screen readers announce backslash-heavy patterns, so if accessibility of shared code matters, test it with the assistive technology your readers actually use. When you share a pattern with a non-developer audience, also describe in plain words what it matches.

Limits of this review

This overview relies on the documented behavior of Groovy string literals and the Java regex API. No specific online escaping tool, Groovy version difference or benchmark was tested, so no claims are made about third-party escaping utilities or performance. If you rely on an edge case, such as dollar signs inside slashy strings or Unicode escapes inside a pattern, confirm it with a short assert in the Groovy version you deploy.