Sub topic 8
Extracting the first match with REGEXEXTRACT
This chapter assumes you can enter formulas, reference cells, and nest functions such as TRIM and IFERROR. It also assumes you know that text in a formula goes inside double quotes. You should have read the previous chapter on regular expression basics. Here you will use those patterns inside a real function.
What REGEXEXTRACT does
REGEXEXTRACT searches a piece of text for a pattern and returns the part of the text that matched. Unlike SPLIT, it does not cut the text at separators. You describe the thing you want, and the function returns that thing.
The syntax has two arguments:
=REGEXEXTRACT(text, regular_expression)textis the cell or string to search.regular_expressionis the pattern, written as a string in RE2 syntax.
The function returns the first match only. If the text contains three numbers, you get one of them. This chapter explains how the "first" match is chosen and what the function returns when the pattern has no groups. The next chapters cover parentheses (capture groups), missing matches, and number conversion.
A first worked example
Put this text in cell A2:
Invoice 2024-0381 due 15 MarEach formula below searches A2 and returns one piece of it.
| Formula | Result | Why |
|---|---|---|
| `=REGEXEXTRACT(A2, "\d+")` | 2024 | The first run of digits, reading left to right |
| `=REGEXEXTRACT(A2, "\d{4}-\d{4}")` | 2024-0381 | Four digits, a hyphen, then four digits |
| `=REGEXEXTRACT(A2, "[A-Z][a-z]{2}$")` | Mar | A capital letter and two lowercase letters at the very end |
| `=REGEXEXTRACT(A2, "\d+$")` | #N/A | The text ends in "Mar", so no digits sit at the end |
Notice that the pattern does not have to describe the whole cell. \d+ ignores everything around the digits. This differs from functions that need the whole value to fit a format. Add ^ (start of text) or $ (end of text) when you want to pin the match to an edge, as the third formula does.
How the first match is chosen
The regular expression engine works through the text from left to right. At each position it tries the pattern. The first position where the pattern fits becomes the match, and the engine stops looking. Two rules decide the exact result.
- Leftmost wins. The match that starts earliest in the text is returned, even if a longer or better match exists further right.
- Greedy by default. Quantifiers such as
+,*, and{n,m}take as much text as they can while still letting the whole pattern match.
The greedy rule explains a common surprise. Suppose A3 contains:
<b>bold</b> and <i>italic</i>=REGEXEXTRACT(A3, "<.+>")This returns the whole string from the first < to the last >, because .+ grabs as much as it can. To stop at the first closing bracket, either use a negated character class or make the quantifier lazy by adding ?:
=REGEXEXTRACT(A3, "<[^>]+>")=REGEXEXTRACT(A3, "<.+?>")Both return <b>. The negated class [^>] means "any character except >". It is usually easier to read and easier to debug than a lazy quantifier.
What gets returned
When the pattern contains no parentheses, the function returns the full matched text. The result is always text, even when it looks like a number. In the table above, 2024 is the string "2024", not the number 2024. Later in this tutorial you will convert it with VALUE. For now, watch for the clue that Sheets gives you: text is left-aligned by default and numbers are right-aligned.
If the pattern does contain parentheses, the function returns the contents of the groups instead of the full match. The chapter on capture groups covers this. One consequence matters now: parentheses used only for grouping change your output. If you need grouping without changing the result, use a non-capturing group, written (?:...).
Non-text input
REGEXEXTRACT converts its first argument to text before searching. A number cell such as 12345 works with \d+ and returns "12345". Dates are the trap here. A date cell is usually converted to its underlying serial number (something like 45000), not to the text you see on screen. If you need to search the displayed form, wrap the cell in TEXT, for example TEXT(A2, "yyyy-mm-dd").
Writing patterns inside a formula
The pattern is an ordinary string, so two quoting rules apply.
- Backslashes are written as they are. Sheets does not treat
\as an escape character in strings, so"\d+"is correct. Do not double it to"\\d+"the way you might in Python or JavaScript. - A double quote inside the pattern is written twice. To extract a quoted phrase from
He said "hello" today, use:
=REGEXEXTRACT(A4, """[^""]+""")The outer quotes open and close the string. Each "" inside stands for one literal quote character. The result is "hello", with the quotes included.
To match a character that has special meaning in a pattern, put a backslash before it. The special characters include ., +, *, ?, (, ), [, ], {, }, |, ^, $, and \. For example, \. matches a literal period, while a bare . matches any character.
Case sensitivity
Matching is case sensitive by default. "usd" will not match USD. Turn on case-insensitive matching with the (?i) flag at the start of the pattern:
=REGEXEXTRACT("Total: USD 45", "(?i)usd")This returns USD, as written in the text. The flag affects matching only. It never changes the case of the returned text.
Extracting an email address
The topic's email formula is a good test of everything so far:
=REGEXEXTRACT(A2, "[\w.+-]+@[\w-]+\.[\w.]+")Read it in three parts:
[\w.+-]+matches one or more word characters, dots, plus signs, or hyphens. This is the part before the@.@is a literal at sign.[\w-]+\.[\w.]+matches the domain: a name, a literal dot, then the rest.
This works for clean text, but it has a gotcha. In Contact: [email protected]. the final [\w.]+ also accepts the sentence-ending period, so the result is x.com. with a trailing dot. A tighter pattern requires each dot to be followed by word characters:
=REGEXEXTRACT(A2, "[\w.+-]+@[\w-]+(?:\.[\w-]+)+")Here (?:\.[\w-]+)+ means "a dot and a label, repeated one or more times". A trailing period has no label after it, so the repetition stops before it. The non-capturing (?: keeps the function returning the whole match.
No short pattern accepts every valid address and rejects every invalid one. Treat this one as a practical extractor for ordinary text, not as validation.
Applying it to a whole column
A normal formula handles one row. To run REGEXEXTRACT over a range, wrap it in ARRAYFORMULA:
=ARRAYFORMULA(REGEXEXTRACT(A2:A10, "\d+"))This puts the results in a single column, one per input row. A row with no match shows #N/A in its own cell and does not affect the other rows. The next chapters show how to replace those errors cleanly.
Be careful with empty cells. An empty cell searched with a pattern that needs at least one character gives #N/A. A pattern that can match nothing, such as \d*, succeeds with an empty string, so a miss produces a blank cell and no error. That can hide problems, so prefer + over * when you expect at least one character.
Checking your results
Three quick checks help when a result looks wrong.
- Test the pattern in a helper column. Put
=REGEXMATCH(A2, "pattern")beside your data to see which rows match at all. - Look for leading or trailing spaces. Invisible spaces change what
^and$mean. Wrap the cell inTRIMfirst:REGEXEXTRACT(TRIM(A2), "..."). - Check the left-to-right rule. If you get a different number than expected, an earlier piece of text probably matched first.
Exercise
Cell A2 contains Ref: ab-77, then AB-1205 and ab-9. (1) What does =REGEXEXTRACT(A2, "[a-z]+-\d+") return? (2) Which flag makes the same pattern return ab-77 while also being able to match AB-1205, and what changes in the pattern? (3) Write a formula that returns the email-like text [email protected] from Mail [email protected]. without the trailing period.
Show answer
(1) It returns ab-77. The pattern is case sensitive, and ab-77 is the leftmost place where lowercase letters, a hyphen, and digits fit. (2) Add (?i) at the start: "(?i)[a-z]+-\d+". It still returns ab-77 because that is the leftmost match, but it would now also match AB-1205 if that came first. (3) =REGEXEXTRACT(A2, "[\w.+-]+@[\w-]+(?:\.[\w-]+)+"). The (?:...) group repeats only when a dot is followed by word characters, so the final period is left out and the whole match is returned.