Regex - Character classes: Simple examples


Sun Mar 21 2021 08:40:14 GMT+0000 (UTC)

Saved by @FlorianC #python #regex

import re

print("[Pp]ython", "Python"))
print("[a-z]way", "The end of the highway"))
print("cloud[a-zA-Z0-9]", "cloudy"))

# put ^ before a character class to search for anything but the given character class
print("[^a-zA-Z]", "This is a sentence with spaces."))

# | as OR operator
print("cat|dog", "I like dogs."))
print(re.findall(r"cat|dog", "I like both cats and dogs."))

The desired character classes are defined within square brackets. The "search" function only returns the first matching entry.