Regex - Character classes: Simple examples
Sun Mar 21 2021 08:40:14 GMT+0000 (Coordinated Universal Time)
Saved by
@FlorianC
#python
#regex
import re
print(re.search(r"[Pp]ython", "Python"))
print(re.search(r"[a-z]way", "The end of the highway"))
print(re.search(r"cloud[a-zA-Z0-9]", "cloudy"))
# put ^ before a character class to search for anything but the given character class
print(re.search(r"[^a-zA-Z]", "This is a sentence with spaces."))
# | as OR operator
print(re.search(r"cat|dog", "I like dogs."))
print(re.findall(r"cat|dog", "I like both cats and dogs."))
content_copyCOPY
The desired character classes are defined within square brackets.
The "search" function only returns the first matching entry.
Comments