Google Sheets – Using REGEXREPLACE to Surround Numbers by Parentheses

google sheetsregex

The data I'm starting with:

1 Hello
2 Just another 22 line
300 Yeah, the first step is to admit you need help

I want the "finished" version to look like:

(1) Hello
(2) Just another (22) line
(300) Yeah, the first step is to admit you need help

To recap: surround any numbers with parentheses.

I can identify the numbers easily in the REGEXREPLACE "find" section, with [0-9]+

I am completely lost in the replace section. How do I retain the matched string?

Best Answer

If your text is in cell A1, then

=regexreplace(A1, "([0-9]+)", "($1)")

will do the job. The term you were looking for is capturing: the parentheses around [0-9]+ capture the matched substring, i.e., it gets recorded somewhere. In the substitution string, the commands $1, $2, ... can be used to refer to the 1st, 2nd, etc captured string.

So, the command says: find a string of consecutive digits (greedily, i.e., grab all consecutive ones), and replace it by the same string surrounded by parentheses. And being a global search-and-replace, regexreplace does the above to every matched substring.