Python3 regular expressions

Python uses re library for regular expressions. re comes with standard python installation. Regular expressions is a very big topic. This page only covers the basics of how to search and substitute. The syntax for patterns is the same as Perl. Consider the following example:

import re

line = "apple banana carrot date eggplant fig guava"

# is there a match?
if re.search("carrot", line):
    print('match found')
else:
    print('match not found')

# what was matched?
mat = re.search(r'(.*) date (.*)', line)
if mat:
    print(mat.group())
    print(mat.group(1))
    print(mat.group(2))
else:
    print('no')

# how to match and substitute a substring
res = re.sub(r'guava', "grapefruit", line)
if res:
    print(res)
else:
    print('not substitution')

output

match found
apple banana carrot date eggplant fig guava
apple banana carrot
eggplant fig guava
apple banana carrot date eggplant fig grapefruit

First, we need to import re. The two function of re that we are interested in a re are search and sub. Search finds the substring (m// in Perl). sub finds and substitutes the substring with another (s/// in Perl).