Download Cheat sheet PDF 12 pages · syntax, editors, patterns, Unicode, performance, debugging
Guide

Escaping special characters

Regex has about a dozen metacharacters with special meaning. If you want them treated literally, you have to escape them with a backslash.

The metacharacters

These need escaping outside character classes to be treated as themselves:

.  *  +  ?  ^  $  |  (  )  [  ]  {{  }}  \

Forward slash / needs escaping only when it would close a regex literal (in JS, Perl, Ruby) — inside a string in Python, Java, etc., it doesn't.

Inside character classes the rules change

Once you're inside [...], most metacharacters are literal. The ones still special are:

]   closes the class — escape to use literally
^   only special at the start (means "negate")
-   only special between characters (means "range")
\   escape character itself

So [.+*] matches a dot, plus, or asterisk — no escaping needed. Compare with .+* outside a class, which is gibberish (asterisk applies to nothing).

Escape sequences with special meaning

A backslash before some characters creates a meta-token rather than escaping a literal:

\d  any digit
\w  word character
\s  whitespace
\b  word boundary
\n  newline
\t  tab
\r  carriage return
\0  null character
\xHH  byte with hex value HH
\uHHHH  Unicode code point HHHH

The uppercase variants negate: \D non-digit, \W non-word, \S non-whitespace, \B not-a-word-boundary.

String escaping vs regex escaping

If your regex is built from a string literal (most languages), you have two escape layers. The string parser sees the source first, then the regex engine sees what's left.

In JavaScript, new RegExp("\d") doesn't do what you might think — the string sees \d as not-a-valid-escape and warns, or treats the backslash as a literal. You need new RegExp("\\d"): the string becomes \d, then the regex engine sees \d = digit.

Regex literals (/\d/) skip this layer — the parser only sees the regex syntax, no string escaping.

Python raw strings (r"\d") similarly skip string escaping.

Programmatic escaping

If you have user input and want to match it literally inside a regex, escape every metacharacter. JavaScript:

function escapeRegex(s) {{
  return s.replace(/[.*+?^${{}}()|[\]\\]/g, '\\$&');
}}

Python uses re.escape(s). Java has Pattern.quote(s). PHP has preg_quote(s). Use these instead of rolling your own — the language built-ins know the edge cases.

Quick reference

The shortest answer to "do I need to escape X?" is: paste the pattern into the explainer. If it parses and means what you want, you're done. If you see "Parse error" or the explanation doesn't match your intent, add a backslash and try again.


← Back to guides