Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle: Replacing non-numeric chars in a string

I have a field in my database where users have saved free-form telephone numbers. As a result, the data has all sorts of different formatting:

  • (area) nnn-nnnn
  • area-nnn-nnnn
  • area.nnn.nnnn
  • etc

I would like to strip out all the non-numeric characters and just store the digits, but I can't find a simple way to do this. Is it possible without using one REPLACE for each char?

like image 274
chris Avatar asked Oct 19 '10 12:10

chris


People also ask

How do I remove non numeric characters from a string?

In order to remove all non-numeric characters from a string, replace() function is used. replace() Function: This function searches a string for a specific value, or a RegExp, and returns a new string where the replacement is done.

How do you delete an alphanumeric character in Oracle?

select regexp_REPLACE('305N','[:alpha:]','') NUM from Dual; Please suggest me.


2 Answers

You can use REGEXP_REPLACE since Oracle 10:

SELECT REGEXP_REPLACE('+34 (947) 123 456 ext. 2013', '[^0-9]+', '') FROM DUAL 

This example returns 349471234562013.

Alternative syntaxes include:

  • POSIX character classes:

    '[^[:digit:]]+' 
  • Perl-influenced extensions (since Oracle 11):

    '\D+' 
like image 166
Álvaro González Avatar answered Sep 23 '22 04:09

Álvaro González


For older versions of Oracle that don't support regular expressions:

select translate (phone_no,'0'||translate (phone_no,'x0123456789','x'),'0') from mytable; 

The inner translate gets all the non-digit characters from the phone number, and the outer translate then removes them from the phone number.

like image 20
Tony Andrews Avatar answered Sep 22 '22 04:09

Tony Andrews



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!