Python String Pattern Matching


String Pattern Matching

For using String Pattern Matching you need to import the re module. With the regular expressions from the re module you can process strings.

Examples

Extract from the string

>>> import re
>>> re.findall(r'\bp[a-z]*','learn fast python language')
['python']
>>> 

Extract groups from string with match object

>>> import re
>>> x = re.match(r"(\d+)\.(\d+)\.(\d+)","34.789.123")
>>> x.groups()
('34', '789', '123')
>>> 

Split string

>>> import re
>>> re.split('[a-z]+','0a1f3C5d7F12v',flags=re.IGNORECASE)
['0', '1', '3', '5', '7', '12', '']
>>> re.split('[a-d]+','0a1f3C5d7F12v',flags=re.IGNORECASE)
['0', '1f3', '5', '7F12v']
>>> re.split('[a-f]+','0a1f3C5d7F12v',flags=re.IGNORECASE)
['0', '1', '3', '5', '7', '12v']
>>> re.split('[a-e]+','0a1f3C5d7',flags=re.IGNORECASE)
['0', '1f3', '5', '7']
>>> re.split('[a-f]+','0a1f3C5d7',flags=re.IGNORECASE)
['0', '1', '3', '5', '7']
>>>