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
3# The string you want to find a pattern within
4test_string = 'Hello greppers!'
5
6# Creating a regular expression pattern
7# This is a simple one which finds "Hello"
8pattern = re.compile(r'Hello')
9
10# This locates and returns all the occurences of the pattern
11# within the test_string
12match = pattern.finditer(test_string)
13
14# Outputs all the ocurrences which were returned as
15# as match objects
16for match in matches:
17 print(match)
18
19
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
1if pattern := re.search("[iI] am (.*)", "I am tired"):
2 print(f"Hi {pattern.group(1)}, I'm dad!")