Sub topic 3
Capture groups: returning several parts at once
Prerequisites: You can enter formulas, reference cells and ranges, and write text in double quotes. You know that TRIM and IFERROR take arguments. You have read the earlier chapters on SPLIT and REGEXEXTRACT basics.
Capture groups
A capture group is a part of a regular expression wrapped in parentheses. REGEXEXTRACT returns the text matched by each group, and the results spill into adjacent cells, one group per column.
=REGEXEXTRACT(A2, "([A-Z]+)-(\d+)")If A2 contains ORD-10492 and the formula sits in B2, B2 shows ORD and C2 shows 10492. A pattern with no groups returns the whole match as one value.
Handling rows with no match
When no text matches, REGEXEXTRACT returns #N/A. Wrap it in IFERROR to show a blank instead:
=IFERROR(REGEXEXTRACT(A3, "\d+"), "")Turning extracted text into numbers
REGEXEXTRACT returns text, even when the text contains only digits. Sums and comparisons can fail on text, so convert the result with VALUE:
=VALUE(REGEXEXTRACT(A2, "\d+"))> Text values align left in a cell and numbers align right. Check the alignment to confirm a conversion worked.
Note: the callout format below replaces the block quote above in the final chapter.
Putting it together
=ARRAYFORMULA(IFERROR(VALUE(REGEXEXTRACT(TRIM(A2:A), "\d+")), ""))This formula trims stray spaces, extracts digits from every row, converts them to numbers, and blanks out rows with no digits.
Pitfalls
Blocked spill ranges
If a cell in the path of a spilled result contains data, the formula returns #REF! with the message "Array result was not expanded." Clear the cells to the right of the formula.
Whitespace
Leading or trailing spaces can stop a pattern from matching where you expect. Apply TRIM first.
Escaping
In Google Sheets, type \d and \. directly in the formula. Do not double the backslashes.
Exercise
Exercise
What does =IFERROR(VALUE(REGEXEXTRACT(A2, "\d+")), 0) return when A2 contains only the word "none"?
Show answer
It returns 0. REGEXEXTRACT returns #N/A because there are no digits, and IFERROR replaces that error with 0.