Regex Escaper
Escape a literal string so it can be used safely inside a regular expression without its characters acting as syntax.
Everything you type here is processed on your own device. No input is sent to a server, logged, or stored.
What the Regex Escaper does
Use this regex escaper to escape a literal string so it can be used safely inside a regular expression without its characters acting as syntax. Paste your text in, pick the options you need, and copy the result straight back out. It is most often used for building a regex from a user-supplied search term. More utilities in this area are collected on FreeToolStation.org.
How to use it
- Paste the literal text you want to match.
- Pick the regex flavour you are targeting.
- Copy the escaped string into your pattern.
How it works
The characters that need escaping in a regular expression are . * + ? ^ $ { } ( ) | [ ] and the backslash itself. Any of them in a literal search string will be interpreted as syntax: a full stop matches any character, a question mark makes the preceding item optional, and an unmatched bracket is a syntax error that throws.
This matters most when the search term comes from user input. Building a regex by concatenating an unescaped user string is both a correctness bug and a denial-of-service risk, because a crafted pattern can cause catastrophic backtracking that hangs the process on a short input.
Most languages have this built in and it is better to use theirs: Python has re.escape, PHP has preg_quote, Java has Pattern.quote, Go has regexp.QuoteMeta. JavaScript is the notable gap — there is no built-in escape, which is why this pattern gets copied into so many codebases.
If you only need a literal match, do not use a regex at all. indexOf, includes or a plain string comparison is faster, clearer and cannot be made to backtrack.
When to use it
- Building a regex from a user-supplied search term.
- Matching a literal string that contains regex metacharacters.
- Escaping a file path or URL for use in a pattern.
- Fixing a pattern that throws a syntax error on certain inputs.
Common mistakes to avoid
- Concatenating unescaped user input into a regex, which is both a bug and a denial-of-service risk.
- Using a regex where a plain string comparison would do.
- Forgetting that the escaping rules differ slightly between flavours.
Frequently asked questions
Which characters need escaping in a regex?
The metacharacters . * + ? ^ $ { } ( ) | [ ] and the backslash. Different flavours add a few more.
Does JavaScript have a built-in regex escape?
No, which is why this pattern is copied into so many codebases. Python, PHP, Java and Go all provide one.
Why is unescaped user input in a regex dangerous?
Beyond matching the wrong thing, a crafted pattern can cause catastrophic backtracking — exponential time on a short input, which hangs the process.