Regex tester · Guide

Regex Match Brackets: Escaping Metacharacters Correctly

Matching a literal metacharacter means escaping it — but the set of characters that need escaping changes depending on whether you are inside a character class, and getting that wrong produces patterns that match far more than intended.

Outside a character class

These twelve are special and need a backslash to match literally: . ^ $ * + ? ( ) [ ] { } | — and \ itself:

Regex
\[.*?\]        # matches [anything] including the brackets
\(\d+\)        # matches (123)
\{.*?\}        # matches {json-ish}
\\             # matches one literal backslash
:              # colon is NOT special — no escape needed

The colon, comma, hyphen (outside a class), slash and quotes are not metacharacters. Escaping them is harmless but adds noise, and \: is an error in some strict engines.

Inside a character class

Almost nothing is special inside [...]. Only ], \, ^ (first position) and - (between two characters) need care:

Regex
[(){}[\]]      # all bracket types — only ] needs escaping
[.*+?]         # literal dot, star, plus, question mark
[a\-z]         # literal hyphen, not a range
[-az]          # hyphen first is also literal
[^]]           # anything except a closing bracket

Placing - first or last in the class avoids escaping it entirely, which is the conventional style.

The backslash multiplier

To match one literal backslash the regex is \\. In a language without raw strings, the string literal doubles it again — so Java and C# without @ need "\\\\" for a single backslash.

This is why raw strings matter: Python r"\\", C# @"\\", and JavaScript regex literals /\\/ all keep the pattern readable. A Windows path pattern written without them becomes unmaintainable quickly.

Escaping dynamically

Never build a pattern by concatenating user input — a stray ( breaks compilation and a crafted input can create a catastrophic pattern. Use the escape helper:

Python
re.escape(user_input)              # Python
preg_quote($input, '/')            # PHP
Pattern.quote(input)               # Java
Regex.Escape(input)                # C#
// JavaScript has none built in:
input.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')

Frequently asked questions

Do I need to escape a colon?

No. The colon is not a regex metacharacter.

Why do I need four backslashes?

Two for the regex, doubled again by a language without raw string literals.

How do I match a literal hyphen in a character class?

Put it first or last, or escape it: [-az], [az-] or [a\-z].

Ready to try it?

Open the free browser-based Regex tester and apply what you just read — no sign-up, runs locally.

Open the Regex tester tool