Nearby lessons

129 of 159

Python - Regex Predefined Character Classes

📌 What You Will Learn
  • Identify the important predefined character classes used in Python regular expressions
  • Understand what s, S, d, D, w, W, and the dot represent
  • Run a demo program with output for each predefined character class using re.finditer()
  • Explain the opposite pairs s ↔ S, d ↔ D, and w ↔ W
  • Compare character classes with predefined character classes using tables

Introduction to Predefined Character Classes

Python Regular Expressions provide several Predefined Character Classes.

These classes are already defined with special meanings, so we do not need to manually write large Character Classes every time.

The important Predefined Character Classes are:

s
S
d
D
w
W
.
        

Simple Definition:

Predefined Character Classes are special Regular Expression symbols that represent commonly used groups of characters.

For example:

d → Any digit

w → Any word character

s → Any whitespace character
        

Predefined Character Classes - Overview

Pattern Meaning
s Space character / whitespace character
S Any character except whitespace
d Any digit from 0 to 9
D Any character except a digit
w Any word character — alphanumeric character or underscore
W Any character except a word character
. Any character, including special characters, except newline by default

s - Whitespace Character

The Predefined Character Class:

s
        

represents a whitespace character.

It can match whitespace characters such as:

  • Space
  • Tab
  • Newline

For the document's target string:

a7b k@9z
        

there is one space character.

a 7 b   k @ 9 z
      ↑
    Space
        

Therefore, s matches that space.

Consider the target string:

Character : a 7 b   k @ 9 z
Index     : 0 1 2 3 4 5 6 7
        

At index 3, we have a space.

Since s represents whitespace:

Index 3 → Space → Match
        

Hence the output contains the match at index 3.

The matched value may look blank because the actual matched character itself is a space.

🐍Code Cell
1import re
2 
3matcher = re.finditer("\s", "a7b k@9z")
4 
5for match in matcher:
6 print(match.start(), "...", match.group())
Output
3 ...

S - Except Whitespace

The Predefined Character Class:

S
        

means:

Any character except a whitespace character.

It is the opposite of s.

s → Whitespace

S → Non-whitespace
        

For:

a7b k@9z
        

every character except the space at index 3 matches.

The target string contains one whitespace character at index 3.

0 → a → Match
1 → 7 → Match
2 → b → Match
3 →   → No Match
4 → k → Match
5 → @ → Match
6 → 9 → Match
7 → z → Match
        

Therefore, every character except the space is returned.

🐍Code Cell
1import re
2 
3matcher = re.finditer("\S", "a7b k@9z")
4 
5for match in matcher:
6 print(match.start(), "...", match.group())
Output
0 ... a
1 ... 7
2 ... b
4 ... k
5 ... @
6 ... 9
7 ... z

d - Digit Character

The Predefined Character Class:

d
        

represents a digit.

For basic ASCII digits, it corresponds to:

[0-9]
        

That means:

0
1
2
3
4
5
6
7
8
9
        

For the target:

a7b k@9z
        

the digits are:

7
9
        

Check the target string:

Character : a 7 b   k @ 9 z
Index     : 0 1 2 3 4 5 6 7
        

The digit characters are:

7 → index 1
9 → index 6
        
🐍Code Cell
1import re
2 
3matcher = re.finditer("\d", "a7b k@9z")
4 
5for match in matcher:
6 print(match.start(), "...", match.group())
Output
1 ... 7
6 ... 9

D - Except Digit

The Predefined Character Class:

D
        

means:

Any character except a digit.

It is the opposite of d.

d → Digit

D → Non-digit
        

Therefore, letters, spaces and special characters can match D.

The digits 7 and 9 do not match.

All remaining characters match:

a
b
space
k
@
z
        

Therefore:

0 → a
2 → b
3 → space
4 → k
5 → @
7 → z
        
🐍Code Cell
1import re
2 
3matcher = re.finditer("\D", "a7b k@9z")
4 
5for match in matcher:
6 print(match.start(), "...", match.group())
Output
0 ... a
2 ... b
3 ...
4 ... k
5 ... @
7 ... z

w - Word Character

The Predefined Character Class:

w
        

represents a word character.

For the basic examples in this tutorial, it includes:

  • Alphabet symbols
  • Digits
  • Underscore _

It can be remembered approximately as:

[a-zA-Z0-9_]
        

For:

a7b k@9z
        

the matching characters are:

a
7
b
k
9
z
        

The space and @ do not match.

Check every character:

Index Character Type Match?
0aAlphabetYes
17DigitYes
2bAlphabetYes
3SpaceWhitespaceNo
4kAlphabetYes
5@Special CharacterNo
69DigitYes
7zAlphabetYes

Important Note: For simple English examples, we commonly remember:

w ≈ [a-zA-Z0-9_]
        

But in Python 3, w is Unicode-aware by default.

So it can also match many Unicode letters and numbers, not only English A-Z and a-z.

For the examples in this tutorial, remembering letters + digits + underscore is sufficient.

🐍Code Cell
1import re
2 
3matcher = re.finditer("\w", "a7b k@9z")
4 
5for match in matcher:
6 print(match.start(), "...", match.group())
Output
0 ... a
1 ... 7
2 ... b
4 ... k
6 ... 9
7 ... z

W - Except Word Character

The Predefined Character Class:

W
        

means:

Any character except a word character.

It is the opposite of w.

w → Word Character

W → Non-word Character
        

For the current target, the non-word characters are:

Space
@
        

The following characters are word characters:

a
7
b
k
9
z
        

Therefore, they do not match W.

The remaining characters are:

Index 3 → Space
Index 5 → @
        

Both are non-word characters and therefore match.

🐍Code Cell
1import re
2 
3matcher = re.finditer("\W", "a7b k@9z")
4 
5for match in matcher:
6 print(match.start(), "...", match.group())
Output
3 ...
5 ... @

. - Dot Character Class

The dot:

.
        

is a special Predefined Character Class.

By default, it matches:

Any character except a newline character.

It can match:

  • Alphabet characters
  • Digits
  • Spaces
  • Special characters

For the target:

a7b k@9z
        

all eight characters match.

The target does not contain a newline.

Therefore, every character is matched:

0 → a
1 → 7
2 → b
3 → space
4 → k
5 → @
6 → 9
7 → z
        

This demonstrates that dot is a very broad pattern.

Important Note About Dot:

Normally:

.
        

does not match a newline character.

Example:

A
B
        

If the target contains an actual newline between A and B, normal dot matching skips that newline.

Python can change this behaviour by using the re.DOTALL flag, but that advanced option is not required for understanding the basic predefined Character Class.

🐍Code Cell
1import re
2 
3matcher = re.finditer(".", "a7b k@9z")
4 
5for match in matcher:
6 print(match.start(), "...", match.group())
Output
0 ... a
1 ... 7
2 ... b
3 ...
4 ... k
5 ... @
6 ... 9
7 ... z

Complete Demo Program

The following is the complete demo program used for every Predefined Character Class in this section.

🐍Code Cell
1import re
2 
3matcher = re.finditer("\s", "a7b k@9z")
4 
5for match in matcher:
6 print(match.start(), "...", match.group())
Output
No output captured.

How to Test Every Pattern

We can use the same program and change only the Regular Expression.

Start with:

matcher = re.finditer("\s", "a7b k@9z")
        

Then test:

s
S
d
D
w
W
.
        

The target string remains:

a7b k@9z
        

This makes it easy to compare the behaviour of all Predefined Character Classes.

The output for every pattern is:

Pattern: s

3 ...
        

Pattern: S

0 ... a
1 ... 7
2 ... b
4 ... k
5 ... @
6 ... 9
7 ... z
        

Pattern: d

1 ... 7
6 ... 9
        

Pattern: D

0 ... a
2 ... b
3 ...
4 ... k
5 ... @
7 ... z
        

Pattern: w

0 ... a
1 ... 7
2 ... b
4 ... k
6 ... 9
7 ... z
        

Pattern: W

3 ...
5 ... @
        

Pattern: .

0 ... a
1 ... 7
2 ... b
3 ...
4 ... k
5 ... @
6 ... 9
7 ... z
        

Complete Target String Analysis

The target string used in this section is:

a7b k@9z
        
Index Character Type
0aAlphabet / Word / Non-space / Non-digit
17Digit / Word / Non-space
2bAlphabet / Word / Non-space / Non-digit
3SpaceWhitespace / Non-word / Non-digit
4kAlphabet / Word / Non-space / Non-digit
5@Special / Non-word / Non-space / Non-digit
69Digit / Word / Non-space
7zAlphabet / Word / Non-space / Non-digit

Positive and Opposite Predefined Classes

Several Predefined Character Classes occur in opposite pairs.

Pattern Meaning Opposite Opposite Meaning
s Whitespace S Non-whitespace
d Digit D Non-digit
w Word character W Non-word character

A useful memory rule is:

Lowercase → Matches that category
Uppercase → Opposite of that category

s ↔ S
d ↔ D
w ↔ W
        

Character Classes vs Predefined Character Classes

Character Class Related Predefined Class Meaning in Basic Examples
[0-9] d Digit
[^0-9] D Non-digit
[a-zA-Z0-9_] w Word character
[^a-zA-Z0-9_] W Non-word character

Note: Python's default Unicode behaviour means d and w can match more Unicode characters than the simple ASCII ranges shown above. The ranges are useful for understanding the introductory examples.

Complete Comparison Table

Pattern Meaning Matches in a7b k@9z
s Whitespace Space
S Except whitespace a, 7, b, k, @, 9, z
d Digit 7, 9
D Except digit a, b, Space, k, @, z
w Word character a, 7, b, k, 9, z
W Except word character Space, @
. Any character except newline by default Every character in this target

Complete Explanation of the Demo Program

Consider:

import re

matcher = re.finditer("\d", "a7b k@9z")

for match in matcher:
    print(match.start(), "...", match.group())
        

Step 1:

import re
        

imports the Regular Expression module.

Step 2:

re.finditer("\d", "a7b k@9z")
        

searches the target for characters matching d.

Step 3:

Python checks the target from left to right.

a → No
7 → Yes
b → No
space → No
k → No
@ → No
9 → Yes
z → No
        

Step 4:

For every successful match, finditer() provides a Match Object.

Step 5:

match.start()
        

returns the starting index.

Step 6:

match.group()
        

returns the actual matched character.

Therefore:

1 ... 7
6 ... 9
        

Execution Flow

Program Starts
      │
      ▼
Import re
      │
      ▼
Select Predefined
Character Class
      │
      │
      ├── s
      ├── S
      ├── d
      ├── D
      ├── w
      ├── W
      └── .
      │
      ▼
Target String
"a7b k@9z"
      │
      ▼
re.finditer()
      │
      ▼
Start from Index 0
      │
      ▼
Check Current Character
Against Pattern
      │
   ┌──┴───┐
   │      │
 Match   No Match
   │      │
   ▼      ▼
Create   Continue
Match    Searching
Object
   │
   ▼
match.start()
match.group()
   │
   ▼
Print Result
   │
   ▼
Move to Next Character
   │
   ▼
Repeat Until
End of String
   │
   ▼
Program Ends
        

Execution Example with d:

Pattern = d
Target  = a7b k@9z

             Start
               │
               ▼
Index 0 → a → No Match
               │
               ▼
Index 1 → 7 → Match
               │
               ▼
          Print 1 ... 7
               │
               ▼
Index 2 → b → No Match
               │
               ▼
Index 3 → Space → No Match
               │
               ▼
Index 4 → k → No Match
               │
               ▼
Index 5 → @ → No Match
               │
               ▼
Index 6 → 9 → Match
               │
               ▼
          Print 6 ... 9
               │
               ▼
Index 7 → z → No Match
               │
               ▼
              End
        

Quick Revision

s → Space / Whitespace

S → Except Space / Whitespace


d → Digit

D → Except Digit


w → Word Character

W → Except Word Character


.  → Any Character Except Newline by Default
        

Remember the three important opposite pairs:

s ↔ S

d ↔ D

w ↔ W
        
📝 Key Takeaways
  • Predefined character classes are special regular expression symbols that represent commonly used groups of characters
  • s matches a whitespace character, d matches a digit, and w matches a word character
  • Uppercase classes S, D, and W match the opposite of their lowercase counterparts
  • The dot . matches any character except a newline by default
  • re.finditer() finds all matching occurrences, match.start() returns the position, and match.group() returns the matched character

🧠 Test Your Knowledge

10 Questions
Progress: 0 / 10