Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle Regexp to replace \n,\r and \t with space

Tags:

I am trying to select a column from a table that contains newline (NL) characters (and possibly others \n, \r, \t). I would like to use the REGEXP to select the data and replace (only these three) characters with a space, " ".

like image 271
Tuti Singh Avatar asked May 06 '13 20:05

Tuti Singh


People also ask

What is CHR 10 and CHR 13 in Oracle?

CHR(10) -- Line feed. CHR(13) -- Carriage return. You can use them in insert like this, INSERT INTO table_name (columne_name) VALUES ('ABC' || CHR (9) || 'DEF' || CHR (10) || 'GHI' || CHR (13) || 'JKL') Here is the complete list of ascii values. http://www.asciitable.com/

What is the use of Regexp_replace in Oracle?

The Oracle/PLSQL REGEXP_REPLACE function is an extension of the REPLACE function. This function, introduced in Oracle 10g, will allow you to replace a sequence of characters in a string with another set of characters using regular expression pattern matching.

What does REGEXP_LIKE return?

The REGEXP_LIKE scalar function returns a boolean value indicating if the regular expression pattern is found in a string. The function can be used only where a predicate is supported. The schema is SYSIBM. An expression that specifies the string in which the search is to take place.


2 Answers

No need for regex. This can be done easily with the ASCII codes and boring old TRANSLATE()

select translate(your_column, chr(10)||chr(11)||chr(13), '    ') from your_table; 

This replaces newline, tab and carriage return with space.


TRANSLATE() is much more efficient than its regex equivalent. However, if your heart is set on that approach, you should know that we can reference ASCII codes in regex. So this statement is the regex version of the above.

select regexp_replace(your_column,  '([\x0A|\x0B|`\x0D])', ' ') from your_table; 

The tweak is to reference the ASCII code in hexadecimal rather than base 10.

like image 99
APC Avatar answered Oct 22 '22 02:10

APC


select translate(your_column, chr(10)||chr(11)||chr(13), ' ') from your_table;

to clean it is essential to serve non-null value as params ... (oracle function basically will return null once 1 param is null, there are few excpetions like replace-functions)

select translate(your_column, ' '||chr(10)||chr(11)||chr(13), ' ') from your_table;

this examples uses ' '->' ' translation as dummy-value to prevent Null-Value in parameter 3

like image 43
Ma Ha Avatar answered Oct 22 '22 01:10

Ma Ha