Hone

Lessons · Regex · group(0): the whole match

Zero is the whole match

group(0) is everything the pattern matched; the numbered groups start at 1 and are counted by their opening brackets, left to right.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Pulling two fields out of one line is most of what capture groups are for, and getting the numbers wrong is silent: you get the wrong field, not an error.

How to think about it

Count opening brackets from the left. Nothing about what matched decides the number, which is why inserting a bracket renumbers everything after it.

Worked example

re.search(r'(\w+)@(\w+)', 'ada@work').group(0)
Everything the pattern matched.
re.search(r'(\w+)@(\w+)', 'ada@work').group(1)
The first opening bracket.
re.search(r'((a)b)', 'ab').group(2)
Nested: the outer bracket opened first, so the inner one is 2.

Your turn

Take just the part before the @.

re.search(r'(\w+)@(\w+)', 'ada@work').group()

The trap

Adding a group anywhere renumbers every group after it. Names survive that; numbers do not.

Practise group(0): the whole match on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.