PostgreSQL – How to Clean Non-Digit Except + at Beginning with Regexp_Replace

postgresqlregex

Related to a comment, I would like to find a way to clean with regexp_replace in PostgreSQL any non-digit except the + at beginning of the string.

For example +(7)9125415501 shall become +79125415501

Best Answer

You can anchor the first character to be replaced to the begin of the string and search for everything not 0 - 9 or + and assert with a look behind, that any other replacement is preceded by any character, hence it's not the begin of the string.

regexp_replace('+(7)9125415501', '^[^0-9\+]|(?<=.)[^0-9]', '', 'g')

Look behinds were introduced in version 9.6. If you're on anything lower than that you can only use look aheads. You can do so reversing the string and instead of looking behind and anchoring for the beginning look ahead and anchor for the end. Rereverse it in the end.

reverse(regexp_replace(reverse('+(7)9125415501'), '[^0-9](?=.)|[^0-9\+]$', '', 'g'))