Extract part of a regex match
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Capturing groups in regular expressions let you extract specific parts of a match rather than the entire matched string. Parentheses () define these groups, and every major language provides access to group contents through the match object. Named groups make the extracted values self-documenting. This technique is essential for parsing log files, extracting data from structured text, and validating input formats.
Python
Use re.search() or re.match() and access groups by index or name.
Extracting Multiple Matches
Use re.findall() or re.finditer() to extract groups from all matches in a string.
JavaScript
Use String.match(), RegExp.exec(), or named groups with (?<name>...) syntax.
All Matches with matchAll
Go
Go uses regexp.FindStringSubmatch for numbered groups. Named groups are accessed via SubexpNames.
Non-Capturing Groups
Use (?:...) when you need grouping for alternation or repetition but do not want to capture the content.
Non-capturing groups keep group indexes clean when you only need specific parts of the match.
Common Pitfalls
- Forgetting that group index 0 is the entire match, not the first group —
match.group(0)returns the full matched string,match.group(1)returns the first captured group. - Using
re.findall()with groups and expecting full match strings — when groups are present,findallreturns group tuples, not full matches. - Not escaping parentheses in the pattern when matching literal
()characters — use\(and\)for literal parentheses. - Nesting groups without tracking index offsets — deeply nested groups shift the index of subsequent groups. Named groups avoid this confusion.
- Using greedy quantifiers inside groups when lazy is needed —
(.*)captures as much as possible, while(.*?)captures the minimum. This matters when multiple groups appear in the same pattern.
Summary
- Use
()to create capturing groups and extract specific parts of a regex match. - Access groups by index (
group(1)) or by name (group("name")) with(?P<name>...)syntax. - Use
(?:...)for non-capturing groups when you need grouping without extraction. - Use
findallorfinditer(Python),matchAll(JavaScript), orFindAllStringSubmatch(Go) for multiple matches. - Named groups make extracted values self-documenting and reduce index-tracking errors.

