Sub topic 9
Capture Groups: Returning Several Parts at Once
This chapter assumes you can enter Google Sheets formulas, reference cells and ranges, and use basic functions such as TRIM and IFERROR. You should also know that text inside a formula is written in double quotes.
What a capture group does
A capture group is a pair of parentheses in a regular expression. It marks the part of a match that you want REGEXEXTRACT to return separately.
For example, this text contains an order code:
Ticket ORD-10492 is readyThe code has two useful parts:
ORD, the letter prefix10492, the numeric part
The hyphen separates the parts, but you may not want the hyphen in either result. Put parentheses around each part:
([A-Z]+)-(\d+)The first group, ([A-Z]+), matches one or more uppercase letters. The second group, (\d+), matches one or more digits.
Returning several columns
If cell A2 contains Ticket ORD-10492 is ready, enter this formula in B2:
=REGEXEXTRACT(A2, "([A-Z]+)-(\d+)")Google Sheets returns the two capture groups into adjacent cells:
| B2 | C2 |
|---|---|
| ORD | 10492 |
When a regular expression has capture groups, REGEXEXTRACT returns the text matched by each group. It spills the results horizontally, so the cells to the right must be empty.
A pattern without capture groups returns the complete matching text:
=REGEXEXTRACT(A2, "[A-Z]+-\d+")This returns ORD-10492 as one value. Adding parentheses changes the output into separate values.
Designing groups carefully
Each pair of parentheses creates another returned column. For an identifier such as US-ORD-10492, use three groups:
([A-Z]{2})-([A-Z]+)-(\d+)The formula is:
=REGEXEXTRACT(A2, "([A-Z]{2})-([A-Z]+)-(\d+)")The results are:
| B2 | C2 | D2 |
|---|---|---|
| US | ORD | 10492 |
The order of the output columns follows the order of the opening parentheses. Design the pattern from left to right in the same order as the fields you want returned.
A group can also capture an email address in separate pieces:
=REGEXEXTRACT(A2, "([\w.+-]+)@([\w-]+)\.([\w.]+)")For [email protected], the results are sam.lee, example, and com. The backslash before the period matters. A plain period means “any character” in a regular expression, while \. means a literal period.
Spill behavior and errors
If the cells to the right already contain data, Sheets cannot place all captured values. Clear the required output cells or move the formula to an empty area.
A row with a different format may also fail to match. For example, a pattern requiring uppercase letters will not match ord-10492. Use a pattern that reflects the actual data, or normalize the input before extraction.
If a row might not contain an order code, wrap the formula with IFERROR:
=IFERROR(REGEXEXTRACT(A2, "([A-Z]+)-(\d+)"), "")This keeps unmatched rows blank instead of showing an error.
Exercise
Cell A2 contains INV-7305. Which formula returns INV in B2 and 7305 in C2?
Show answer
=REGEXEXTRACT(A2, "([A-Z]+)-(\d+)")