A character class is a regular-expression construct written inside square brackets. It matches one character from the listed set, such as [aeiou] for vowels or [yY] for either case of Y. section 8.3.2 section 15.1.5
Use character classes to describe allowed or excluded characters:
- List individual characters: [aeiou] matches one lowercase vowel, while [<>] matches either angle bracket. section 8.3.2 section 17.1.1
- Combine ranges: [a-zA-Z] matches ASCII lowercase or uppercase letters. section 20.3.1
- Negate a class with ^ as its first character: [^<>] matches characters other than angle brackets, and [^a-zA-Z] excludes nonletters. section 17.1.1 section 20.3.1
- Repeat a class with a quantifier: [consonants]+ matches one or more consecutive consonants. section 14.1.2
Replace vowels with re.sub()
import re pattern = '[aeiou]' re.sub(pattern, 'o', 'Apples and bananas!') # 'Applos ond bononos!' Apply a second class, '[AEIOU]', when uppercase vowels must become 'O'. Character classes let the pattern declare what to find while re.sub() performs the replacement. section 8.3.2
Validate a fixed-format string
import re board = '.' * 9 re.search('^[.XO]{9}$', board) # <re.Match object; span=(0, 9), match='.........'> Here [.XO] permits a dot, X, or O; {9} requires exactly nine characters; ^ and $ anchor the complete string. section 21.2.1
>>> re.search('<[^<>]+>', text)
<re.Match object; span=(10, 21), match='<adjective>'>
Inspect a negated character class that avoids both angle brackets when matching placeholder contents. section 17.1.1
>>> pattern = '[' + consonants + ']' >>> pattern '[bcdfghjklmnpqrstvwxyz]'
Build a consonant character class dynamically, then use it with re.match() to find leading consonants. section 14.1.2








