Developer tools

Regex Escape

Regex Escape Tool

Escape special characters so literal text is safe inside a regular expression, for JavaScript, Python, POSIX or a character class.

About this tool

About Regex Escape

When you build a regex from user input, a file name or a price like $9.99, characters such as . $ ( and ? stop being text and start acting as operators. This tool adds a backslash in front of every character that has a special meaning, so the pattern matches your text exactly and nothing else. Choose the rules you need: JavaScript escapes the full set including / so the result works in both new RegExp() and a /…/ literal, with or without the u flag; Python follows the behaviour of re.escape() in Python 3.7 and later; POSIX ERE suits grep -E, sed -E and awk; and Inside [ ] escapes only the four characters that matter within a character class. The Ready to paste box turns the result into working code. Unescape goes the other way, turning \. back into a dot and \x41 into A, and it refuses classes like \d that stand for many characters. Everything runs locally in your browser.

Built and maintained by Abhi JainUpdated

How to Escape Text for a Regex

  1. 1

    Pick the direction

    Leave Direction on Escape, or choose Unescape to turn an escaped pattern back into plain text.

  2. 2

    Choose the syntax

    Select JavaScript, Python re.escape, POSIX ERE or Inside [ ].

  3. 3

    Enter the text

    Type or paste into Literal text; the escaped version appears on the right as you type.

  4. 4

    Copy

    Copy the escaped text, or copy the code from Ready to paste.

Regex Escape: questions and answers

Which characters need escaping in a regex?

In JavaScript: . * + ? ^ $ { } ( ) | [ ] \ and, inside a /…/ literal, the forward slash /. Inside a character class only \ ] [ ^ and - need escaping. Letters and digits must not be escaped, because \d, \w or \b have special meanings.

How do I escape a string for RegExp in JavaScript?

Replace each special character with a backslash plus the character: str.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&'). Newer engines also offer RegExp.escape(), which escapes even more characters for extra safety. This tool produces the same safe result.

What does Python's re.escape do?

Since Python 3.7, re.escape() puts a backslash before regex-special characters and some whitespace and symbols, such as . ^ $ * + ? { } [ ] \ | ( ) - # & ~ and space, and leaves letters, digits and underscore alone. The Python option here follows the same rules.

Why do backslashes double in new RegExp strings?

In a JavaScript string literal, a backslash is itself an escape character, so the regex \. must be written "\\." inside quotes. The Ready to paste box shows both forms so you don't have to count backslashes.