Python 3 Regex: Named Capture Examples
Last updated:Table of Contents
- Extract Named capture groups
- Re.search
- Search, multiple matches
- Re.findall
- Findall, multiple matches
Extract Named capture groups
re.match
only matches at the start of the string!
Extract matches into a dict, using re.match
and .groupdict()
:
import re
# a word followed by a comma and then another word followed by a period
pattern = r'(?P<param1>[\w]+),(?P<param2>[\w]+)\.'
re.match(pattern,'foo,bar.').groupdict()
# >>> {'param1': 'foo', 'param2': 'bar'}
Re.search
re.search
matches anywhere in the string!
import re
# a word followed by a comma and then a word followed by a period
pattern = r'(?P<param1>[\w]+),(?P<param2>[\w]+)\.'
re.search(pattern,'xxx foo,bar.')
# >>> <re.Match object; span=(5, 13), match='foo,bar.'>
Search, multiple matches
import re
# a word followed by a comma and then a word followed by a period
pattern = r'(?P<param1>[\w]+),(?P<param2>[\w]+)\.'
matches = re.search(pattern,' foo,bar. aaaand another xxx,yyy.')
for match in matches.groups():
print(match)
# >>> foo
# >>> bar
Re.findall
re.findall
returns a list of matches
import re
# a word followed by a comma and then another word followed by a period
pattern = r'(?P<param1>[\w]+),(?P<param2>[\w]+)\.'
re.findall(pattern,'foo,bar.')
# >> [('foo', 'bar')]
Findall, multiple matches
import re
# a word followed by a comma and then another word followed by a period
pattern = r'(?P<param1>[\w]+),(?P<param2>[\w]+)\.'
re.findall(pattern,'foo,bar. and another xxx,yyy.')
# >>> [('foo', 'bar'), ('xxx', 'yyy')]