Python regular expression module (re) can be used to check a string begins with a pattern using re.match(). Note that it is different from re.search() as it matches pattern from the beginning. Basic usage of re.match() is:
re.match(pattern, string, flags=0)
Here are some examples.
re.match – ignore case
We can use flag re.I (or re.IGNORECASE) for ignoring case.
import re m = re.match('hello', "Hello WORLD", re.I) if (m): print m.group()
Hello
Env: Python 2.7.18
re.match – with sub groups
Round brackets in pattern can be used for subgroups matching and can be accessed using m.groups().
import re m = re.match('(hello)\s+(world)', "Hello WORLD test", re.I) if (m): print m.group() print m.groups()
Hello WORLD ('Hello', 'WORLD')
Env: Python 2.7.18