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
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"