Regex · <code>[abc]</code> matches a, b or c

Character classes

Square brackets match one character from a set, with ranges, negation and shorthand classes such as \d and \w.

Key facts

Set<code>[abc]</code> matches a, b or c
Range<code>[a-z]</code> matches one lowercase letter
Negation<code>[^0-9]</code> matches anything but a digit
Shorthand<code>\d</code>, <code>\w</code>, <code>\s</code>
Literal dashFirst or last position, or escaped as <code>\-</code>
Literal bracket<code>\]</code> or first position
JavaScript<code>\d</code> is ASCII 0–9 even with the u flag
Python<code>\d</code> matches Unicode decimal digits by default

One character, one set

A class matches exactly one character. gr[ae]y matches “gray” and “grey”; [0-9]{3} matches three digits. Ranges are defined by code-point order, so [A-z] also includes punctuation between Z and a — a classic bug when the intent was letters only.

To include a literal hyphen, put it first or last, or escape it. To include a closing bracket, escape it or place it first. Caret negates only when it is the first character inside the brackets.

Shorthand classes and Unicode

\d, \w and \s are conveniences with engine-specific definitions. In JavaScript, \d is always [0-9] and \w is [A-Za-z0-9_], even under the u flag; \s includes many Unicode whitespace characters. In Python 3, \d and \w match Unicode digits and letters by default, which changes what “digit” means for Arabic-Indic numerals.

When the input can be non-ASCII, write the class explicitly or use Unicode property escapes such as \p{L} in engines that support them. Explicit classes cost a few characters and remove a category of silent mismatch.

Frequently asked questions

What is the difference between [abc] and (abc)?

Square brackets match one character from the set. Parentheses group a sequence and capture it, so (abc) matches the three characters in order.

Why does [A-z] match punctuation?

Ranges follow code-point order, and the characters between Z and a include [ \ ] ^ _ and the backtick. Use [A-Za-z] for letters.

Does \d match non-ASCII digits?

Not in JavaScript. Python and some other engines match Unicode digits by default, so the answer depends on the engine.

New tools, straight to your inbox

One short email when we add tools worth using. No spam, unsubscribe anytime.