/codes/regex/regex-shorthand-character-classes
Regex shorthand classes: \d \w \s \b and POSIX [:alpha:]
- tool
- Regex
- versions
- Python 3, PCRE2, POSIX
- os
- any
Shorthand classes are escapes that stand for a set of characters. \d is a digit, \w a word character (letters, digits, underscore), \s whitespace; the uppercase forms \D, \W, \S match everything else. \b is not a character but a position between a word character and a non-word character. In POSIX tools (grep -E, sed, awk) use bracket classes such as [[:digit:]] instead.
Shorthands
| Escape | Matches | ASCII equivalent |
|---|---|---|
| \d / \D | digit / non-digit | [0-9] / [^0-9] |
| \w / \W | word character / other | [A-Za-z0-9_] / [^A-Za-z0-9_] |
| \s / \S | whitespace / other | [ \t\n\r\f\v] / its complement |
| \b / \B | word boundary / not a boundary | (a position, zero width) |
POSIX bracket classes
| Class | Matches |
|---|---|
| [[:digit:]] | digits |
| [[:alpha:]] [[:alnum:]] | letters, letters and digits |
| [[:upper:]] [[:lower:]] | upper-case, lower-case letters |
| [[:space:]] [[:blank:]] | whitespace, space and tab only |
| [[:punct:]] | punctuation |
| [[:xdigit:]] | hexadecimal digits |
They only work inside a bracket expression: [[:digit:]]+, not [:digit:]+.
Unicode changes the answer
python - <<'EOF'
import re
text = "año 2026 ٣ naïve_x"
print(r"\w+ (Unicode, default) ", re.findall(r"\w+", text))
print(r"\w+ with re.ASCII ", re.findall(r"\w+", text, re.ASCII))
print(r"\d (Unicode, default) ", re.findall(r"\d", text))
print(r"\d with re.ASCII ", re.findall(r"\d", text, re.ASCII))
print(r"\bx\b ", re.findall(r"\bx\b", "x x_y y-x"))
EOFOutput
\w+ (Unicode, default) ['año', '2026', '٣', 'naïve_x'] \w+ with re.ASCII ['a', 'o', '2026', 'na', 've_x'] \d (Unicode, default) ['2', '0', '2', '6', '٣'] \d with re.ASCII ['2', '0', '2', '6'] \bx\b ['x', 'x']
In Python 3 str patterns, \d also matches digits from other scripts (٣ is Arabic-Indic three) and \w includes accented letters; re.ASCII restricts both to ASCII. In JavaScript \d and \w are always ASCII-only, even with the u flag; use \p{Nd} and \p{L} for Unicode.