Google Sheets Function: REGEXREPLACE
The REGEXREPLACE function replaces one or more parts of a text using regular expressions.
Usage:
=REGEXREPLACE(text, regular_expression, replacement)
Simple Replacement
The REGEXREPLACE function here replaces the word "fun" with "enjoyable":
=REGEXREPLACE(A2,"fun","enjoyable")
The problem with this formula is that if the text contains the word "funny", it will be replaced by "enjoyableny" (as you can see in the colored cell).
To avoid this, you must specify that "fun" can be followed by "ny":
=REGEXREPLACE(A2,"fun(ny)?","enjoyable")
Removing Characters
To remove all non-numeric characters (to keep only phone numbers, for example), enter the regex "\D"
and replace these characters with an empty string ""
:
=REGEXREPLACE(A2,"\D","")
Replace Email Addresses
The following formula detects and replaces email addresses (this regex is detailed in one of the examples of the REGEXMATCH function):
=REGEXREPLACE(A2,"[\w.-]+@[\w.-]{2,}\.[a-z]{2,}","[email address removed]")
To remove only the first part of the email address and replace it with "xxxxxx", enclose the second part to be kept in parentheses and add it to the replacement address using $1:
=REGEXREPLACE(A2,"[\w.-]+(@[\w.-]{2,}\.[a-z]{2,})","xxxxxx$1")