Oracle trim whitespace on the inside of a string
Asked Answered
R

2

24

I am storing phone numbers as VARCHAR2 in my system to allow for users to input '+' characters infront of their phone number if they so choose.

My regexp allows for this perfectly, but when storing the number in the database I want to strip out all whitespace the user may enter.

My regexp allows for the following formats

+4470123456789
+447 0123456789
+447 01234 56789
01234567890
01234 567890
01234 567 890

I know I could resolve my issue by not letting users put any whitespace in their numbers, but I know from personal experience just how frustrating it is to have a validation error due to some silly formatting on the client side. I have tried using the TRIM function on my INSERT/UPDATE trigger but I have realised that is limited to only front and trailing whitespace, is there any other function in Oracle I could use that would remove internal whitespace? Or do I need to write my own function to do this?

Any pointers would be greatly appreciated.

Ribald answered 31/1, 2014 at 16:10 Comment(0)
J
58

You want to try replace (telno, ' ', '').

Jenjena answered 31/1, 2014 at 16:11 Comment(2)
Hi , what can i do if i want to replace the space and convert phone number from varchar2 to number?Goosy
to_number(replace(telno, ' ', ''))Aguirre
L
7

a better approach is to use a regular expression to remove all spaces within a string

SQL> with t as (
    select 'AAA    BBB CCC' col from dual union
    select 'DDDD EEE     F' col from dual 
    )
    --
    -- actual query:
    --
    select regexp_replace(col, '[[:space:]]+', chr(32)) col
    from   t;

COL

AAA BBB CCC DDDD EEE F

Liquidize answered 31/12, 2019 at 5:44 Comment(4)
Why do you suggest that regular expression is better than replace()? Regular expression processing is much more CPU intensive in general.Epigrammatize
Do not understand why people are forcing themselves to use regular expression on such a simple need.Picoline
This regex answer collapses whitespace vs the replace answer removes whitespace in the middle. Regex can accomplish either answer's solution whereas replace cannot.Wayland
The regex answer includes all forms of whitespace (space, tab, vertical space) whereas the simple replace only catches space characters. In other words, for example, tabs will be ignored I believe.Praiseworthy

© 2022 - 2024 — McMap. All rights reserved.