Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
61 views

9 Python Regex Group Functions

The document discusses Python regex group functions including the group() method to retrieve matched groups by name and the groupdict() method to return a dictionary of matched groups. It provides an example of using named groups and printing the matches, as well as an example of using groupdict() to return a dictionary of matches.

Uploaded by

ArvindSharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views

9 Python Regex Group Functions

The document discusses Python regex group functions including the group() method to retrieve matched groups by name and the groupdict() method to return a dictionary of matched groups. It provides an example of using named groups and printing the matches, as well as an example of using groupdict() to return a dictionary of matches.

Uploaded by

ArvindSharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Python regex `group` functions

Python Regex group() function explained with examples: named groups and groupdict.

WE'LL COVER THE FOLLOWING

• Group dictionary Groupdict

A regular expression can have named groups. This makes it easier to retrieve
those groups after calling match() . But it makes the pattern more complex.

Following example shows a named group ( first and last ).

#!/usr/bin/python
import re

# A string.
name = "Learn Scientific"

# Match with named groups.


m = re.match("(?P<first>\w+)\W+(?P<last>\w+)", name)

# Print groups using names as id.


if m:
print(m.group("first"))
print(m.group("last"))

We can get the first name with the string “first” and the group() method. We
use “last” for the last name.

Group dictionary Groupdict #


A regular expression with named groups can fill a dictionary. This is done
with the groupdict() method. In the dictionary, each group name is a key and
Each value is the data matched by the regular expression. So we receive a key-
value store based on groups.

import re

name = "Scientific Python"

# Match names.
m = re.match("(?P<first>\w+)\W+(?P<last>\w+)", name)

if m:
# Get dict.
d = m.groupdict()

# Loop over dictionary with for-loop.


for t in d:
print(" key:", t)
print("value:", d[t])

You might also like