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

Negated Shorthands — \D \W \S

~5 min · shorthand, negation

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

Capital letter flips the meaning

Every shorthand has a capital-letter inverse:

  • \D — NOT a digit. Same as [^\d].
  • \W — NOT a word character. Same as [^\w].
  • \S — NOT whitespace. Same as [^\s].

That's the whole rule. Lowercase = the set, uppercase = the complement.

Real-world uses

\D+ is great for splitting: re.split(r'\D+', '2026-05-04') gives ['2026', '05', '04']. The non-digits between are eaten as the delimiter.

\S+ is a clean way to grab "runs of non-whitespace" — tokens, URLs, file paths.

\W is useful for finding word boundaries you control more tightly than \b can express.

Same Unicode caveats apply

Whatever flavor / flag controls the lowercase form controls the uppercase too. Python 3 default makes \D exclude every Unicode digit, not just ASCII 0-9.

Code

Negated shorthand patterns·python
import re

# Split on non-digits — extract numbers from a date
re.split(r'\D+', '2026-05-04')
# ['2026', '05', '04']

# Grab non-whitespace tokens
re.findall(r'\S+', 'hello world  \tfoo\nbar')
# ['hello', 'world', 'foo', 'bar']

# Find non-word characters (punctuation, symbols)
re.findall(r'\W', 'hello, world! 안녕?')
# [',', ' ', '!', ' ', '?']  — depends on Unicode mode

External links

Exercise

Take a messy string like ' apple , banana ; cherry ' and use one regex split to get a clean list ['apple', 'banana', 'cherry']. Hint: combine \W+ with strip().

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.