Skip to content

/codes/regex/regex-shorthand-character-classes

Regex shorthand classes: \d \w \s \b and POSIX [:alpha:]

verified onenvironmentlocal · windows 10.0.26200 arm64 · GNU bash 5.3.15 (Git Bash) · grep (GNU grep) 3.0updated 2026-10-20
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

EscapeMatchesASCII equivalent
\d / \Ddigit / non-digit[0-9] / [^0-9]
\w / \Wword character / other[A-Za-z0-9_] / [^A-Za-z0-9_]
\s / \Swhitespace / other[ \t\n\r\f\v] / its complement
\b / \Bword boundary / not a boundary(a position, zero width)

POSIX bracket classes

ClassMatches
[[: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

bash
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"))
EOF

Output

\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.

Sources