python capture regex groups in variables

The below snippet is useful when we have a string and we want to save the pattern in a variable. We can do this using regex, i.e we can capture groups in regex and then access them later using variables,

This is how it is done.

#python script to capture regex matched groups into variables
import re

suffix = 'en'
word = 'children'

#print(word,suffix)

m = re.search(r'(.*)'+suffix + '

, word)

print(m.group(1))

2 thoughts on “python capture regex groups in variables

Leave a Reply

Your email address will not be published. Required fields are marked *