C.W.K.
Stream
Lesson 06 of 12 · published

Shorthand Classes — \d \w \s

~8 min · shorthand, digit, word, whitespace

Level 0Pattern-Curious
0 XP0/90 lessons0/15 achievements
0/100 XP to next level100 XP to go0% complete

Three letters that save you typing

The most common character classes have shorthand forms. They mean exactly what they look like:

  • \d — a digit. ASCII: [0-9]. Unicode-mode: any Unicode digit.
  • \w — a "word" character. ASCII: [A-Za-z0-9_]. Unicode-mode: letters + digits + connectors.
  • \s — a whitespace character. [ \t\n\r\f\v], plus Unicode whitespace in Unicode mode.

These are universal — every regex flavor supports them.

Unicode-aware vs ASCII-only

This is where flavors diverge subtly:

  • Python 3: \d, \w, \s default to Unicode-aware. \d matches Arabic-Indic digits, Devanagari digits, etc. Use the re.ASCII flag to force ASCII-only.
  • JavaScript: ASCII-only by default. The u flag enables Unicode but doesn't change \w to include Unicode letters. Use \p{L} with u flag for that.
  • RE2 / Go / ripgrep: ASCII by default. Use \p{Nd}, \pL etc for Unicode categories.
  • PCRE: ASCII by default; (*UCP) or /u mode enables Unicode-aware.

The \w trap

\w includes underscore but NOT hyphen. So \w+ matches my_var but not my-var. People constantly forget this. If you want "identifier-like with hyphens," use [\w-]+ explicitly.

Code

Shorthand classes·python
import re

# Numbers in any text
re.findall(r'\d+', 'on 2026-05-04 at 14:32')
# ['2026', '05', '04', '14', '32']

# Word-like tokens
re.findall(r'\w+', 'hello_world! foo-bar 123')
# ['hello_world', 'foo', 'bar', '123']  — note: '-' splits 'foo-bar'

# Whitespace
re.findall(r'\s+', 'a\tb  c\nd')
# ['\t', '  ', '\n']

# Python 3 default Unicode-aware: matches non-ASCII digits
re.findall(r'\d+', '٢٠٢٦ 2026')
# ['٢٠٢٦', '2026']

# Force ASCII-only
re.findall(r'\d+', '٢٠٢٦ 2026', re.ASCII)
# ['2026']

External links

Exercise

Write three patterns: (1) extract every number from a multi-line log, (2) extract every word-like token, (3) split on any run of whitespace. For each, decide whether you want Unicode-aware or ASCII-only and add the right flag.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.