This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 7: Groups

Non-capturing groups

face Josiah Wang

Sometimes you are just not interested in the content of a group. You might just want to group them together.

You can explicitly represent such non-capturing groups with (?: ). You cannot retrieve the content of such groups.

Below is an example. We do not need to know whether the class is “dog” or “puppy”, so we represent this as a non-capturing group. Examine the output, and you will find that the class has been skipped. Useful if you have too many parentheses and have no need to capture them all!

>>> pattern = "Accuracy: (\d+\.\d+) Class: (?:dog|puppy) Precision: (\d+\.\d+)"
>>> string = "Accuracy: 0.35 Class: dog Precision: 0.55"
>>> match = re.match(pattern, string)
>>> match.groups()
('0.35', '0.55')
>>> match.group(1)
'0.35'
>>> match.group(2)
'0.55'