Regex Usage in Python

Itacen Sabacok | Feb 1, 2022

Python has a package called re for Regular Expressions.


search() Function

Returns a match object if there is a match anywhere in the string

1import re
2
3text = "Everything has beauty, but not everyone can see"
4print(re.search("^Everything.*see$", text))
5
6# OUTPUT
7<re.Match object; span=(0, 47), match='Everything has beauty, but not everyone can see'>

findall() Function

Returns a list containing all matches. It returns an empty list if no match was found

1import re
2
3text = "I wish i were a fish in your dish"
4print(re.findall("ish", text))
5
6# OUTPUT
7['ish', 'ish', 'ish']

split() Function

Returns a list where the string has been split at each match

1import re
2
3text = "split each white-space character"
4x = re.split("\s", text)
5print(x)
6
7# OUTPUT
8['split', 'each', 'white-space', 'character']

sub() Function

Replaces the matches with the text of your choice

1import re
2
3phone_no = '(226)-793-158-08'
4pattern = '\D'
5result = re.sub(pattern, '',phone_no)
6print(result)
7
8# OUTPUT
922679315808

re Module Funtions

Function Description
search Returns a Match object if there is a match anywhere in the string
findall Returns a list containing all matches
split Returns a list where the string has been split at each match
sub Replaces one or many matches with a string