Escape & unescape
Escape text for a regular expression
Turn any string into a pattern that matches it literally, in four regex flavours at once, ready to paste into code. Or go the other way.
JavaScript
Escapes ^ $ \ . * + ? ( ) [ ] { } | and /, which is safe with and without the u and v flags.
Python re
Identical to re.escape() in Python 3.7 and later.
PCRE / PHP
Identical to PHP’s preg_quote() with the delimiter you choose.
POSIX ERE
For grep -E, sed -E and awk. ] and } only need escaping inside a bracket expression.
Why each flavour escapes differently
A regex treats some characters as instructions: . means any character, * repeats, brackets and parentheses group. To match them literally, put a backslash in front. Which characters need it depends on the engine, and escaping too much can itself be an error.
- JavaScript: escapes only the syntax characters and
/. With theuorvflag an unnecessary escape such as\-or\#is a syntax error, so a minimal escape is the safe one. Line breaks are written as\nso the result also works inside a/literal/. - Python: the same set as
re.escape(), which also escapes-,#,&,~and spaces, because they matter in verbose mode and inside classes. - PCRE / PHP: the same as
preg_quote(), plus the delimiter you wrap the pattern in. - POSIX ERE: for
grep -E,sed -Eandawk. The shell form wraps the pattern in single quotes so the shell leaves it alone.
Unescape works the other way: paste an escaped pattern and get the literal text back. If the pattern contains real regex syntax, such as an unescaped dot or a \d, the tool points to the first one instead of guessing.
Questions
Does JavaScript have a built-in escape function?
Newer engines have RegExp.escape(), which also escapes a leading letter or digit and characters such as - and , as hex codes so the result is safe in more contexts. Its output is longer but matches the same text.
Can I use the escaped text inside [ ]?
These escapes are meant for use outside a character class. Inside one, only \, ], ^ and - are special, so escape those instead.
Is my text sent anywhere?
No. Escaping happens in your browser as you type.