Hello! This cheat sheet for you! Enjoy!
Regular expressions in Python are handled using the re
module. Firstly you have to import re module by writing import re
in the first line of your python file.
Regex Patterns:
.
: Any character except a newline.^
: Start of the string.$
: End of the string.*
: Zero or more repetitions.+
: One or more repetitions.?
: Zero or one repetition.{n}
: Exactly n repetitions.{n,}
: At least n repetitions.{n,m}
: Between n and m repetitions.[abc]
: Matches a, b, or c.[^abc]
: Matches any character except a, b, or c.\d
: Matches any digit.\D
: Matches any non-digit.\w
: Matches any word character (alphanumeric plus underscore).\W
: Matches any non-word character.\s
: Matches any whitespace character.\S
: Matches any non-whitespace character.
Basic functions:
re.search()
: Scans through a string, looking for any location where the regex pattern matches.re.match()
: Checks for a match only at the beginning of the string.re.findall()
: Finds all substrings where the regex pattern matches and returns them as a list.re.finditer()
: Finds all substrings where the regex pattern matches and returns them as an iterator of match objects.re.sub()
: Replaces the matches with a specified string.
Examples
print(re.search(r"\d+", "Python is cool! 100 % ! ").group()) # 100
print(re.match(r"\w+", "Hello world").group()) # Hello
print(re.findall(r"\d+", "My 1 Python and my 2 JavaScript")) # ['1', '2']
print(re.sub(r"\d+", "very", "Python is 1 cool and 2 nice.")) # Python is very cool and very nice.
Discover more from Coursity
Subscribe to get the latest posts sent to your email.