2. Groups and positions
Parentheses (...) in a pattern create a capturing group. A group lets you extract one part of the match:
group()orgroup(0)— the whole match.group(n)— the text captured by group numbern. Groups are numbered from1, left to right.groups()— a tuple with every captured group, in order.
re.finditer(pattern, string, flags=0) returns an iterator of match objects, one per occurrence, so you can read each match in a for loop:
finditeraccepts the samepattern,stringandflagsassearch.- It is lazy: it produces one match at a time, left to right, without overlapping.
The r"..." prefix makes a raw string: backslashes are kept for re instead of being interpreted by Python. Use a raw string whenever the pattern contains a backslash; it is also fine to use one every time.
Coming from JavaScript? match.group(1) is close to match[1] in JS; match.groups() is match.slice(1), but Python returns a tuple instead of an array.
Capture one group
Search for the pattern r"Hello (Ada)" in "Hello Ada". The parentheses capture Ada. Print the captured text with .group(1).
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Whole match versus group
Using the same match for r"Hello (Ada)" in "Hello Ada", print .group() on the first line and .group(1) on the second. group(0) is always the whole match; groups start at 1.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Number the groups
Search for r"(Ada) (Lovelace)" in "Ada Lovelace". Groups are numbered left to right. Print .group(1) on one line and .group(2) on the next.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Collect every group
.groups() returns a tuple with all captured groups. Search for r"(Ada) (Lovelace)" in "Ada Lovelace" and print the result of .groups().
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Loop over matches with finditer
re.finditer() returns every match, one at a time. Search for r"(cat)" in "cat dog cat" and loop over the matches. Print the first group of each match on its own line.
Print exactly:
Create a free account to save your progress and unlock chapter 2.