Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle trim whitespace on the inside of a string

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.

like image 500
Halfpint Avatar asked Jan 31 '14 16:01

Halfpint


People also ask

How can remove space in middle of string in Oracle?

Oracle TRIM() function removes spaces or specified characters from the begin, end or both ends of a string.

How do I remove spaces between words in Oracle?

The Oracle TRIM function does not trim spaces between words. You can use a regular expression with REGEXP_REPLACE to remove occurrences of more than once space. Or, you can use the REPLACE function to remove all spaces between words – but this would result in a single long word.

How do I trim a space in Oracle?

The Oracle TRIM function is used to remove all leading or trailing characters (or both) from a character string. If trim_character or trim_source is a character literal, then it is necessary to enclose it in single quotation marks. When no trim_character is specified, then the default value is a blank space.


2 Answers

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

like image 120
René Nyffenegger Avatar answered Oct 24 '22 07:10

René Nyffenegger


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

like image 41
Sarfraz Ahmed Avatar answered Oct 24 '22 07:10

Sarfraz Ahmed