1import re
2# Compile a regular expression pattern into a regular expression object, which can be used for matching using its match(), search() and other methods, described below.
3
4prog = re.compile(pattern)
5result = prog.match(string)
6
7# is equivalent to
8
9result = re.match(pattern, string)
1import re
2# regex for finding mentions in a tweet
3regex = r"(?<!RT\s)@\S+"
4tweet = '@tony I am so over @got and @sarah is dead to me.'
5
6# mentions = ['@tony', '@got', '@sarah']
7mentions = re.findall(regex, tweet)
8
1import re
2
3pattern = '^a...s$'
4test_string = 'abyss'
5result = re.match(pattern, test_string)
6
7if result:
8 print("Search successful.")
9else:
10 print("Search unsuccessful.")
11
1 ## Search for pattern 'bb' in string 'aabbcc'.
2 ## All of the pattern must match, but it may appear anywhere.
3 ## On success, match.group() is matched text.
4 match = re.search(r'bb', 'aabbcc') # found, match.group() == "bb"
5 match = re.search(r'cd', 'aabbcc') # not found, match == None
6
7 ## . = any char but \n
8 match = re.search(r'...c', 'aabbcc') # found, match.group() == "abbc"
9
10 ## \d = digit char, \w = word char
11 match = re.search(r'\d\d\d', 'p123g') # found, match.group() == "123"
12 match = re.search(r'\w\w\w', '@@abcd!!') # found, match.group() == "abc"