Hone

Lessons · Regex · ( ): keeping the part you matched

Capturing a piece

Parentheses make a group: they let a quantifier apply to several characters at once, and they capture the matched text so you can pull it out afterwards.

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

Extracting the area code, the year from a date, the key and value from key=value: the match is not enough, you need the parts, and groups are the parts.

How to think about it

Wrap each piece you want in parentheses, in order. Group 1 is the first opening parenthesis, group 2 the second. Use (?:...) for grouping without capturing when you only need the quantifier.

Worked example

pattern: (\d{4})-(\d{2})-(\d{2})
Three captures: year, month, day.
text: due 2026-09-06
Group 1 = 2026, group 2 = 09, group 3 = 06.
pattern: (\w+)=(\w+)
Key and value.
text: mode=dark
Group 1 = mode, group 2 = dark.

Your turn

Capture the username before the @.

()@\w+

The trap

findall returns only the captured groups when the pattern has any, not the whole match. Add a group around everything, or use finditer, when you need both.

Practise ( ): keeping the part you matched on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.