REGEXREPLACE replaces the parts of text that match a regular expression. SUBSTITUTE replaces a fixed piece of text, so removing every non-digit from a phone number needs a nest of calls, one per symbol. REGEXREPLACE does it with a single pattern that describes what to remove.
Availability
REGEXREPLACE is one of three REGEX functions in Microsoft 365, with REGEXTEST and REGEXEXTRACT. Microsoft has released them in stages, so your build may not have them. There, the formula returns #NAME?. They are not in Excel 2024 or earlier. The practice sheet on this page uses Rangewise's own engine, which does not run them yet. The examples show what Excel returns, and the exercise solves the same problems with the older functions.
The arguments
- text is the text to change.
- pattern is the regular expression that finds what to replace.
- replacement is what to put in. An empty string deletes the matches.
- occurrence is which match to replace. The default
0 replaces them all. - case_sensitivity is case-sensitive by default.
1 ignores case.
Common jobs
Keep only digits. The pattern [^0-9] means "any character that isn't a digit", so =REGEXREPLACE(A2,"[^0-9]","") turns Tel: (02) 5550-0142 into 0255500142. With SUBSTITUTE you would need a call for every symbol.
Remove spaces. =REGEXREPLACE(A2,"\s","") removes every space, tab and line break, because \s stands for any whitespace.
Collapse runs of spaces. =REGEXREPLACE(A2,"\s+"," ") turns any run of whitespace into one space. That is the "between words" part of TRIM, without trimming the ends.
Mask digits. =REGEXREPLACE(A2,"\d","#") replaces every digit with a hash, so Order 7719 becomes Order ####.
Replacing only one match
With occurrence, you can pick a match. =REGEXREPLACE("a-b-c","-","/",2) returns a-b/c. A negative number counts from the end, so -1 changes the last match. SUBSTITUTE does the same with its instance_num, but only for fixed text.
Check the pattern first
A pattern can match more than you expect. Test it on a few values and use REGEXTEST to see which rows it matches before you replace anything. Greedy patterns such as .* can swallow far more text than intended.
The result is text
REGEXREPLACE returns text. After removing the symbols from "1,250", you get "1250" as text. Wrap it in VALUE if you need a number.
Before REGEX
Without REGEXREPLACE, you nest SUBSTITUTE calls for fixed pieces of text, use CLEAN and TRIM for whitespace, and fall back on long MID and FIND combinations for patterns. They work in every version of Excel and they are fine for two or three replacements. A pattern is the better tool when the list of characters to remove is long.