Content · Programming · Python

Python Regex Character Classes and Quantifiers

Match digit, letter, and whitespace classes with quantifiers.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Match digit, letter, and whitespace classes with quantifiers.

How It Works


Character classes such as [A-Z] or \d select characters, while *, +, ? and {n,m} control repetition. By default, shorthand classes can include non-ASCII Unicode characters; use re.ASCII when ASCII-only behavior is required.

Step-by-Step Example


import re
text = 'SKU-4827'
print(re.findall(r'[A-Z]+|\d+', text))
print(bool(re.fullmatch(r'[A-Z]{3}-\d{4}', text)))

Understanding the Example


  • The expression "'SKU-4827'" supplies the value stored as 'text'. This value is then used or checked by the later statements.
  • The print() call exposes the result so you can compare it with the behavior described above. Check the value and its type when experimenting.

A successful run of this example prints the following output:

['SKU', '4827']
True

Where This Fits in a Real Program


Start by writing down examples that should match and examples that must fail. Check whether you need to locate a substring, match a prefix or validate an entire field; these are different operations. Unicode and escape sequences can also change which characters are matched, so test accented text and empty input.

Practice: Try It Yourself


Validate complete input with fullmatch() rather than a partial search.

For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.

Further Reading


Read the official Python documentation for complete parameters, return types and exceptions.

Common Beginner Mistakes


  • Using \d when ASCII digits are required or forgetting to escape special punctuation.
  • Write a pattern that recognizes a two-letter code followed by three digits.

Key Takeaways


  • Match digit, letter, and whitespace classes with quantifiers.
  • Character classes such as [A-Z] or \d select characters, while *, +, ? and {n,m} control repetition.
  • Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.
Share this resourceSend this page to someone who may find it useful.