Sub topic 12
Strip unwanted characters with REGEXREPLACE
This chapter assumes you can enter formulas, you know TRIM, CLEAN, and SUBSTITUTE from earlier chapters, and you know how to wrap a range in ARRAYFORMULA. Here you will learn to remove or rewrite text by pattern instead of by exact match.
Why a pattern tool
SUBSTITUTE replaces one exact string. That is enough for a single known character, such as a non-breaking space. Real data is messier. A phone column might contain (555) 010-1234, 555.010.1234, +1 555 010 1234, and 555-010-1234 ext. 7. You can't list every variant, but you can describe what you want to keep: digits.
REGEXREPLACE finds text that matches a regular expression (a "regex"). A regex is a compact description of a pattern, such as "any character that is not a digit". The function replaces every match with the text you supply.
REGEXREPLACE(text, regular_expression, replacement)textis the cell or string to clean.regular_expressionis the pattern, in quotes.replacementis what to put in place of each match. Use""to delete the matches.
Google Sheets uses the RE2 regex engine. RE2 supports most everyday syntax. It does not support lookaheads, lookbehinds, or backreferences inside the pattern. Keep that in mind when a pattern from another tool fails.
The first pattern: keep only digits
The formula from the plan strips everything that is not a digit.
=REGEXREPLACE(A2, "[^0-9]", "")Read the pattern from the inside out:
[0-9]is a character class. It matches any single digit.^as the first character inside the brackets negates the class.[^0-9]matches any character that is not a digit.- The replacement
""is empty, so every matched character disappears.
(555) 010-1234 becomes 5550101234. The parentheses, space, and hyphen all match the pattern and are removed.
Result type
REGEXREPLACE always returns text. This is often what you want. A phone number or postal code such as 02134 keeps its leading zero as text. If you need a real number, convert it:
=VALUE(REGEXREPLACE(A2, "[^0-9.-]", ""))This turns $1,234.50 into the number 1234.50. The class [^0-9.-] keeps digits, the decimal point, and a minus sign. The hyphen sits last in the class so it is read literally and not as a range.
Pattern building blocks
You need only a small set of regex pieces for most cleanup.
| Pattern | Matches | Example use | Column | Column |
|---|---|---|---|---|
| `[^0-9]` | Any non-digit | Phone numbers, IDs | ||
| `[^A-Za-z ]` | Anything except ASCII letters and spaces | Names with stray symbols | ||
| `\d` | One digit | Building larger patterns | ||
| `\s` | One ASCII whitespace character | Collapsing spacing | ||
| `+` after an item | One or more of it | `\s+` for a run of spaces | ||
| `^` outside brackets | Start of the text | Trim leading characters | ||
| `$` | End of the text | Trim trailing characters | ||
| `\ | ` | Either side | `^\s+\ | \s+$` |
| `(?i)` at the start | Ignore case | `(?i)ext` |
Three details cause most errors:
- Escape special characters. A period, parenthesis, plus sign, question mark, and several others have special meaning. To match a literal period, write
\.. - Quotes inside the pattern. To match a double quote, double it inside the formula string:
"[""]"matches one". - No extra escaping for backslashes. Sheets does not use backslash as a string escape, so write
\d, not\\d.
Spaces and hidden characters
Earlier chapters used SUBSTITUTE with CHAR(160) for non-breaking spaces. REGEXREPLACE can do the same job with a Unicode escape, and it can handle several characters at once.
=REGEXREPLACE(A2, "[\x{00A0}\x{200B}]", " ")\x{00A0} is the non-breaking space. \x{200B} is the zero-width space, which is invisible and has no width at all. Both are common in text copied from web pages. The formula replaces either with a normal space, and TRIM can then clean up the spacing.
To remove all control characters, such as line breaks, tabs, and other non-printing codes, use the Unicode category \p{Cc}:
=REGEXREPLACE(A2, "\p{Cc}", "")This does what CLEAN does and also catches some characters that CLEAN misses. If the cell holds a multi-line address and you want to keep the line breaks as spaces, replace with " " instead of "".
Keep versus remove
You can write a pattern in two ways. A negated class says what to keep: [^A-Za-z0-9 ] deletes everything except letters, digits, and spaces. A positive class says what to remove: [#$%*] deletes only those four symbols.
Choose by how well you know the data:
- Use the negated form when the valid characters are a small, known set, such as digits in a phone number.
- Use the positive form when the valid set is large or open-ended, such as names from many languages.
Reformatting with capture groups
The replacement text can reuse parts of the match. Put parentheses around a part of the pattern to form a capture group. In the replacement, $1 is the first group, $2 is the second, and so on.
This formula first reduces the cell to digits, then formats a ten-digit number:
=REGEXREPLACE(REGEXREPLACE(A2, "[^0-9]", ""), "^(\d{3})(\d{3})(\d{4})$", "($1) $2-$3")The inner call turns any variant into 5550101234. The outer pattern requires exactly ten digits from start (^) to end ($), split into groups of 3, 3, and 4. The replacement rebuilds them as (555) 010-1234.
Because of the anchors, a number with 9 or 11 digits does not match, and the formula returns it unchanged. This is a useful property. Values that fail the pattern stay visible instead of being quietly mangled, so you can find them in the verification step.
Cleaning a whole column
Apply the function to a range with ARRAYFORMULA, as in the earlier TRIM example. Guard against blank cells so the formula doesn't spill empty strings into rows that have no data:
=ARRAYFORMULA(IF(A2:A = "", "", REGEXREPLACE(A2:A, "[^0-9]", "")))REGEXREPLACE also accepts numbers and converts them to text first, so a numeric cell such as 5550101234 passes through without an error.
You can chain it with the other tools. This pipeline removes odd characters, then trims, then standardizes case:
=ARRAYFORMULA(PROPER(TRIM(REGEXREPLACE(A2:A, "[^\p{L} '-]", ""))))The pattern keeps letters from any alphabet, spaces, apostrophes, and hyphens. That preserves names like O'Brien and Mary-Jane. TRIM then collapses the gaps left by removed characters, and PROPER fixes capitalization. Order matters: run REGEXREPLACE before TRIM, because removing characters can leave double spaces.
Choosing between the tools
When in doubt about what a cell contains, inspect it. =LEN(A2) shows the character count, which exposes hidden characters. =CODE(MID(A2, 1, 1)) returns the code of the first character, and you can change the 1 to look at other positions.
Common errors
- The formula returns the text unchanged. The pattern did not match. Check for an unescaped special character, or a character your pattern doesn't cover, such as a non-breaking space.
- A
#VALUE!or "invalid regular expression" error. RE2 rejected the pattern. Unbalanced parentheses and unsupported features such as lookahead are the usual causes. - A number column won't sum. REGEXREPLACE returned text. Wrap the call in
VALUE, or put--in front of it. - Leading zeros vanish. The cleaned result was converted to a number somewhere. Keep identifier columns as text.
- Overly greedy deletion. A negated class removes everything outside it, including characters you didn't think about. Test on a handful of rows before you fill down.
Exercise
Column A contains values such as "Order #A-1042 (rush)" and "Order #B-77". Write a formula for B2 that keeps only the letters and digits, giving "OrderA1042rush" and "OrderB77". Then write a version that fills down the whole column and leaves blank rows empty.
Show answer
For one cell: =REGEXREPLACE(A2, "[^A-Za-z0-9]", ""). The class keeps ASCII letters and digits and deletes everything else, including spaces, "#", "-", and parentheses. For the whole column: =ARRAYFORMULA(IF(A2:A = "", "", REGEXREPLACE(A2:A, "[^A-Za-z0-9]", ""))). The IF test stops the formula from filling empty rows.
Exercise
Cell A2 holds " +1 (555) 010-1234 ". Using the two-step approach from this chapter, write one formula that returns "(155) 501-0123" is NOT what you want; instead explain what the ten-digit formatting formula returns for this cell, and why.
Show answer
The inner call removes every non-digit and gives "15550101234", which has eleven digits because of the leading country code 1. The outer pattern "^(\d{3})(\d{3})(\d{4})$" requires exactly ten digits from start to end, so it does not match, and the formula returns "15550101234" unchanged. This is the intended behavior. The value stays visible so you can find it in your checks. To handle the country code, add an optional prefix to the outer pattern: "^1?(\d{3})(\d{3})(\d{4})$". Then the leading 1 is matched and dropped, and the result is "(555) 010-1234".