Lessons · Regex · capture groups
Capturing the parts
Parentheses group a piece of the pattern and remember what it matched, numbered from 1.
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 year, month, day from a date or level and message from a log line.
How to think about it
Wrap each part you want back in parentheses. Use (?:...) for grouping you do not need to capture.
Worked example
pattern: (\w+)@(\w+)\.comTwo captures.
text: ada@example.comGroup 1 = ada, group 2 = example.
Your turn
Capture hours and minutes from 12:30.
(\d{2}):()Test a pattern against real text
The trap
Groups are numbered by the opening parenthesis, left to right, including nested ones.
Practise capture groups on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.