Regex Character Sets

Carson West

Regex Metacharacters

Regex Character Sets

These notes cover Python’s regular expression character sets. Character sets allow you to match one character from a specified group.

import re

string = "Hello, World! 123"

# Match any lowercase vowel
match = re.findall(r"[aeiou]]", string)  # Output: ['e', 'o', 'o']]

# Match any digit
match = re.findall(r"[0-9]]", string)  # Output: ['1', '2', '3']]

# Match any character except a space
match = re.findall(r"[^ ]]", string) #Output: ['H', 'e', 'l', 'l', 'o', ',', 'W', 'o', 'r', 'l', 'd', '!', '1', '2', '3']]

# Match any uppercase or lowercase letter
match = re.findall(r"[a-zA-Z]]", string) # Output: ['H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd']]

# Matching a literal ]]
match = re.findall(r"1abc]]", "abc1") #Output: ['abc]]']]

#Matching a literal -
match = re.findall(r"[-abc]]", "abc-def") #Output: ['-']]

#Matching a literal ^
match = re.findall(r"[^abc]]", "abc^def") #Output: ['^']]

Character Classes (Escape Sequences) Regex Quantifiers