Oracle: Replacing non-numeric chars in a string

拥有回忆 提交于 2019-12-17 16:04:55

问题


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?


回答1:


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+'
    



回答2:


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.



来源:https://stackoverflow.com/questions/3968178/oracle-replacing-non-numeric-chars-in-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!