32

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?

2 Answers 2

67

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+'
    
Sign up to request clarification or add additional context in comments.

4 Comments

This answer saved my day. Though through a bit of googling I found out that you can replace '[^0-9]+' with '[^[:digit:]]+'. :)
@AmirSyafrudin - That's a POSIX character class. If I recall correctly, they weren't supported in earlier versions, but should work fine with recent releases.
Thanks for the heads up, Alvaro. I got it from here: orafaq.com/node/2404, tested it in my 11g database, and posted my comment above. I guess during the process I kinda forgot to notice which version this is supported. :)
@AmirSyafrudin Please disregard the part about Oracle version. I was confused with PERL-Influenced Extensions such as \d. POSIX syntax was available from the beginning (i.e., 10g).
15

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.

1 Comment

really coll way! I suppose hat regexp take more CPU power instead of translate

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.