Match literal text with special characters using regex

How to make a regex match an exact string containing dots, brackets or dollar signs: escaping, built-in escape functions, extra escaping layers, and when plain search is better.

A regular expression treats some characters as instructions rather than text. To match a literal string such as "price (USD): $4.99", you have to convert it so that every special character stands for itself. This review covers that conversion, called escaping, and whether the result stays correct, readable and portable.

Short answer: when escaping is the right tool

Escaping fits when the literal has to sit inside a larger pattern, or when an API accepts only a regex. A larger pattern might combine the literal with anchors, alternation, a case-insensitive flag or other regex features. The main benefit is exact text matching with the engine's full flexibility around it. The main tradeoff is that an escaped pattern is harder to read. Its correctness also depends on the regex flavor and on every string layer it passes through.

Plain text is the better choice when you only need to find or compare a fixed string. Examples include Python's in operator or str.find, JavaScript's includes or indexOf, Java's String.contains, and fixed-string mode in command-line search tools. These approaches have no escaping step to get wrong.

What escaping actually changes

Escaping changes the pattern, not the text being searched. It adds a backslash before each special character, or wraps the literal in a quoting construct, so the engine reads those characters as ordinary text. The subject string is untouched, and a successful match returns the original, unescaped text.

In most common flavors, these characters are special outside a character class:

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

Inside a character class the rules are different: ], , ^ and - can be special depending on where they appear. Some contexts add more special characters. A forward slash ends a JavaScript regex literal. In extended or verbose mode, # starts a comment and unescaped whitespace is ignored. A literal escaped correctly for one context is not automatically correct in another.

For example, hand-escaping the literal a.b(c) gives:

a\.b\(c\)

Left unescaped, a.b(c) would match "axbc": the dot matches any character and the parentheses only form a group. It would not match the literal text "a.b(c)" at all.

Clearing up "literal" and "string literal"

  • Matching a literal string: making a pattern match exact text. This is the main subject here.
  • A regex literal: pattern syntax written between delimiters, such as /a.b/g in JavaScript, Perl or Ruby. Here the delimiter becomes one more character to escape.
  • Matching string literals in source code: a separate task. It means writing a pattern that recognizes quoted strings, including ones with escaped quotes inside.

For the source-code case, a common pattern for double-quoted strings with backslash escapes is:

"(?:[^"\\]|\\.)*"

This pattern handles escaped quotes. It does not handle language-specific forms such as raw strings, triple-quoted strings or template literals with interpolation. It also cannot tell when a quote appears inside a comment. For anything beyond a quick search, a tokenizer or parser for that language is more reliable.

Use the built-in escape function instead of escaping by hand

Most languages document a standard-library function that escapes text for their own regex flavor:

Language | Escape a literal | Notes
Python | re.escape(s) | Since Python 3.7, escapes only characters that are special
JavaScript | RegExp.escape(s) | Recent addition to the language; check runtime support, fallback below
Java | Pattern.quote(s) | Wraps the text in \Q...\E; alternatively compile with the Pattern.LITERAL flag
C# / .NET | Regex.Escape(s) | Also escapes # and whitespace
Go | regexp.QuoteMeta(s) | Returns a pattern that matches the literal text
PHP | preg_quote(s, delimiter) | Pass the delimiter so it is escaped too
Ruby | Regexp.escape(s) | Regexp.quote is an alias
Perl | quotemeta(s) | Or wrap the text in \Q...\E inside the pattern
Command line | grep -F, rg -F | Treats the pattern as a fixed string, with no regex interpretation

For JavaScript environments without RegExp.escape, this fallback is widely used:

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

This fallback is safe when the result goes into new RegExp() outside a character class. It does not escape - or /, so it is not suitable for text placed inside a character class or pasted into a /.../ literal in source code. Built-in functions may also produce output that looks different from hand escaping. RegExp.escape, for instance, uses hex escapes for some characters. What matters is matching behavior, so test the result rather than comparing pattern text.

Escaping layers: where literal patterns usually break

The regex engine is often not the only thing that reads backslashes. When a pattern is written inside a source-code string, the language's string parser consumes one level of backslashes first. Each line below produces the same regex:

Regex the engine must see:   a\.b
Java / C# string:            "a\\.b"
C# verbatim string:          @"a\.b"
Python raw string:           r"a\.b"
JavaScript regex literal:    /a\.b/
JavaScript constructor:      new RegExp("a\\.b")

Other layers can stack on top. These include storing the pattern in JSON or YAML, passing it through a shell, or embedding it in another pattern. Each layer may double the backslashes again. In POSIX shells, single quotes stop the shell from interpreting backslashes. Calling an escape function at runtime avoids most of this, because it works on the actual string value rather than on source-code text.

Replacement strings follow separate rules, and escaping the search pattern does not protect them. A dollar sign is special in JavaScript, Java and .NET replacement strings, and a backslash is special in Python's re.sub. Each language has a safe option:
• Java: Matcher.quoteReplacement.
• JavaScript: $$ for a literal dollar sign, or a replacement function.
• .NET: $$ for a literal dollar sign.
• Python: a function or lambda as the replacement.

Matching the exact string, not just text that contains it

An escaped literal matches wherever it appears in the input. To require that the whole input equals the literal, add anchors or use a full-match API. Examples are Python's re.fullmatch and Java's String.matches or Matcher.matches.

Anchors have a catch. In Python, Java and PCRE, $ also matches just before a trailing newline, so ^literal$ accepts the literal followed by a newline. In Ruby, ^ and $ always act as line anchors. For the absolute start and end of input, use \A with \Z in Python, or \A with \z in Java, PCRE, Ruby and .NET. In JavaScript without the m flag, $ matches only at the end of input.

Word boundaries can also fail with literals that start or end with punctuation. \bC++\b does not match "C++" followed by a space. The issue is that \b needs a word character on one side, and neither the final + nor the space is one. Lookarounds express "not surrounded by word characters" directly in engines that support them. Go's RE2-based regexp package does not.

(?<!\w)C\+\+(?!\w)

Will the escaped pattern stay correct after copying or sharing?

The matched text is never altered, so the risk lies in the pattern. Patterns usually break when copied between tools, contexts or people:

  • Flavor differences: \Q...\E works in Perl, PCRE and Java, but not in JavaScript or Python's re module. JavaScript with the u or v flag rejects unnecessary escapes such as - outside a character class, while many other engines accept them.
  • Lost or extra backslashes: copying a pattern from a source-code string into a regex tester, or the other way round, brings the wrong number of backslashes.
  • Invisible characters: text copied from documents or web pages may contain non-breaking spaces, zero-width characters or curly quotes. Escaping keeps them as they are, so the pattern silently fails to match text that looks identical.
  • Unicode normalization: "é" can be stored as one code point or as "e" plus a combining accent, and escaping does not reconcile the two forms. Normalize both the literal and the subject to the same form, such as NFC, before matching. Emoji built from several code points, such as joined sequences or ones with variation selectors, match only if every code point is present.
  • JavaScript without the u flag: characters outside the Basic Multilingual Plane, including most emoji, are stored as two code units each. They work as a plain sequence but break inside a character class.
  • Case-insensitive matching: the flag still applies to escaped literals, and case-folding rules for non-ASCII letters vary between engines.

Backslash-dense patterns are hard to scan and review. When sharing one in documentation or code review, put the plain literal next to it. Better still, build the pattern in code by passing a clearly named variable through an escape function, so readers see the original text. The supplied material includes no evidence on how screen readers or particular editors present such patterns, so none is claimed here. For any reader-facing context, providing the plain-text literal is the safer choice.

Editor find dialogs and search tools with a regex option interpret special characters while that option is on. For a literal search, turn regex mode off or use the tool's fixed-string mode.

Security note for user-supplied text

When the literal comes from user input, escape it or use plain string search before putting it into a pattern. Unescaped input can change the pattern's meaning, raise syntax errors, or add quantifiers that cause excessive backtracking. An escaped literal adds no quantifiers or alternation of its own. The surrounding pattern still determines overall matching behavior and performance.

Limits of this review

No test results, performance measurements or environment-specific observations were supplied. The behavior described reflects the documented conventions of each language's regex library and general regex principles. Function availability and edge-case handling can change between versions. Confirm the behavior against the runtime you use, and test with real subject text that includes the edge characters you expect.