Escape special characters in regular expressions
What escaping a regex special character actually changes, which characters need it, how double escaping goes wrong, and when a plain-text search is the better choice.
In a regular expression, some characters are operators rather than literal text. A dot matches any character, a plus sign means "one or more," and parentheses form a group. To match one of these characters literally, you escape it, usually by putting a backslash in front of it. This review covers what escaping changes, which characters are affected, where it causes trouble, and when you can skip regex altogether.
Is escaping the right tool for your task?
Escaping is the right choice when you need literal text inside a larger pattern. A common example is inserting a user-supplied word, file name or price into an expression that also uses anchors, alternation or quantifiers. Its main benefit is that the engine treats the inserted text as text and not as instructions. That prevents mismatches, errors from unbalanced brackets, and patterns that behave differently than intended.
The main drawback is that escaping depends on context. The correct output depends on the regex flavor, on whether the text sits inside or outside a character class, and on how many other layers (string literals, JSON, shell quoting) the pattern passes through. An escape that is correct in one layer can be wrong once it is pasted into another.
If you only need to find a fixed piece of text, plain text is usually the better choice. Most languages offer substring search without regex, such as a contains or index-of method, and many command-line tools have a fixed-string mode, like the -F option of grep. These options need no escaping, which removes a whole category of mistakes.
What escaping actually changes
Escaping changes the stored characters. It does not change how they are displayed. A backslash is inserted before each character that would otherwise have special meaning, so the escaped string is longer than the original and contains real backslash characters. This differs from transformations that only change appearance, such as styling or display direction. It is a change to the text itself, and the regex engine interprets it differently as a result.
The phrase "escape sequence" covers two related things that are easy to mix up. Escaping a metacharacter, such as writing a backslash before a dot, removes its special meaning. Other sequences do the opposite and add meaning to an ordinary letter: backslash-d matches a digit, backslash-w a word character, and backslash-n a newline. Putting a backslash before an arbitrary letter is therefore not a safe way to say "treat this literally" and may produce an error or an unexpected match, depending on the flavor.
Which characters need escaping
Outside a character class, most widely used flavors (including those in JavaScript, Python, Java, .NET, PCRE and Perl) treat the following as metacharacters that need escaping to be matched literally:
- . matches any character except, by default, a newline
- ^ and $ are anchors for start and end
- + ? are quantifiers
- { } are bounded quantifiers
- ( ) form a group
- [ ] form a character class
- | is alternation
- \ is the escape character itself
Inside square brackets the rules are different. Only a few characters are special there: the closing bracket, the backslash, a caret in the first position (negation), and a hyphen between two characters (a range). A dot or plus sign inside brackets is already literal. Escaping it anyway is usually harmless, but strict modes in some engines reject unnecessary escapes.
A few other characters depend on context. A forward slash must be escaped in JavaScript regex literals and in Perl or PHP patterns that use slashes as delimiters, but it is an ordinary character in most other settings. The # character and whitespace become significant in verbose or extended mode, where unescaped spaces are ignored and # starts a comment.
| Context | Needs escaping for a literal match | Notes |
| Outside brackets | . ^ $ * + ? ( ) [ ] { } | \ | Consistent across most mainstream flavors |
| Inside brackets | ] \ and, by position, ^ and - | Other metacharacters are already literal |
| Slash-delimited literal | / | JavaScript literals, Perl, PHP delimiters |
| Verbose or extended mode | spaces, #, other whitespace | Only when that mode is enabled |
Checking an example
Take the input text below. The goal is to match it literally:
price (USD) $5.00?
Applying the outside-brackets list above escapes the parentheses, the dollar sign, the dot and the question mark. Letters, digits and spaces are left alone:
price \(USD\) \$5\.00\?
This is the minimal escaped form. Built-in functions may produce more. In current Python versions, re.escape also escapes spaces and a few other characters so that the result stays safe in verbose mode, which makes it noisier but equivalent. Two escapers can therefore give different output that matches the same text, so differing output alone does not mean an escaper is wrong.
Use the language's own escape function where one exists
Hand-written escaping is where most errors start. Most languages have a built-in function that follows that engine's rules: re.escape in Python, Pattern.quote in Java, Regex.Escape in .NET, preg_quote in PHP (which also takes the delimiter as an argument), and quotemeta or the \Q...\E construct in Perl. Recent JavaScript engines include RegExp.escape. For older environments, a common replacement uses a character class of the metacharacters:
function escapeRegExp(text) {
return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
This fallback escapes the core metacharacters and is fine for inserting text outside a character class. It does not handle the slash for regex literals or the hyphen inside brackets. If the escaped text ends up in either of those places, those characters need extra handling.
Will the escaped pattern still work after copying or sharing?
The most common failure is double escaping, or escaping too little, when a pattern moves between layers. In languages where a backslash is also the string-literal escape, such as Java, C#, JavaScript strings and non-raw Python strings, a regex that needs one backslash has to be written with two in source code. Python raw strings and C# verbatim strings avoid this. A pattern copied from an online tester into source code, a JSON config file or a shell command may need its backslashes doubled, quoted differently, or left alone, depending on where it lands. Test the pattern in the place where it will actually run, not only in the tool where it was built.
Replacement strings follow separate rules. In JavaScript the dollar sign has special meaning in replacement text, and in Python's re.sub the backslash does. Escaping the search pattern does nothing to protect the replacement, so literal replacement text needs its own handling.
Readability gets worse as escapes pile up. A heavily escaped pattern is harder to review and edit. Read aloud by a screen reader, it is likely to be a long run of symbol names, though no specific assistive technology was tested for this article. When people need to read or maintain the pattern, keep the original plain text next to it, in a comment or in documentation, or build the pattern from a variable passed through an escape function. Escaping does not change searchability or Unicode content in the original text. The non-ASCII characters themselves are left alone by mainstream escape functions, and only the added backslashes differ.
Gaps in this review
No specific online escaping tool was tested for this article, so no claims are made about any particular tool's accuracy, flavor support or data handling. If you use a web-based escaper, check which regex flavor it targets, whether it covers character-class and delimiter contexts, and what its own documentation says about how pasted text is processed or stored. Flavor details beyond the mainstream set, such as POSIX basic regular expressions, where some characters reverse their meaning when escaped, are outside the scope of this article and should be checked against that engine's documentation.