oracle正则表达式来格式化电话号码

时间:2018-08-23 20:54:32

标签: sql regex oracle

我想使用case语句和正则表达式组合来格式化以下格式的电话号码

+1 (111) 111-1111111-111-1111

并且当第一个大括号(c)之后的位数计数不等于10时,则为null,否则按原样填充

能否请您提供一些有用的Oracle正则表达式函数来处理此问题

谢谢

2 个答案:

答案 0 :(得分:2)

例如:

SQL> with test (col) as
  2    (select '+2 (123) 123-4433' from dual union all -- convert
  3     select '22 (23)234-443'    from dual union all -- do not convert
  4     select '-3 (123) 345 2343' from dual union all -- do not convert
  5     select '123 345 565'       from dual union all -- do not convert
  6     select '+c (334) abc-1234' from dual           -- do not convert
  7    )
  8  select col,
  9         case when regexp_like(col, '\+\d \(\d{3}\) \d{3}-\d{4}') then
 10                   replace(substr(col, 5, length(col)), ') ','-')
 11              else col
 12         end result
 13  from test;

COL               RESULT
----------------- ----------------------------------------------------
+2 (123) 123-4433 123-123-4433
22 (23)234-443    22 (23)234-443
-3 (123) 345 2343 -3 (123) 345 2343
123 345 565       123 345 565
+c (334) abc-1234 +c (334) abc-1234

SQL>

答案 1 :(得分:1)

您不需要CASE表达式。您可以使用REGEXP_REPLACE并尝试匹配整个字符串。如果找到匹配项,则使用向后引用将数字重新格式化为新模型。如果找不到匹配项,则按原样返回输入字符串。

with test (col) as
  (select '+2 (123) 123-4433' from dual union all -- convert
   select '22 (23)234-443'    from dual union all -- do not convert
   select '-3 (123) 345 2343' from dual union all -- do not convert
   select '123 345 565'       from dual union all -- do not convert
   select '+c (334) abc-1234' from dual           -- do not convert
  )
select col,
       regexp_replace(col, '^\+\d \((\d{3})\) (\d{3}-\d{4})$', '\1-\2') result
from   test
;

COL               RESULT              
----------------- --------------------
+2 (123) 123-4433 123-123-4433        
22 (23)234-443    22 (23)234-443      
-3 (123) 345 2343 -3 (123) 345 2343   
123 345 565       123 345 565         
+c (334) abc-1234 +c (334) abc-1234