Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REGEXP_REPLACE - remove commas from string ONLY if enclosed in ()'s

I find an example at oracle forum site :

Input string : a, b, c (x, y, z), a, (xx, yy, zz), x,

WITH t AS (SELECT 'a, b, c (x, y, z), a, (xx, yy, zz), x,' col1 
         FROM dual)
SELECT t.col1
 , REGEXP_REPLACE(t.col1, '(\(.*?\))|,', '\1') new_col
FROM t

Output : a b c (x, y, z) a (xx, yy, zz) x

But i want to make opposite of that. Just remove this character , from inside () and remain outside.

Output : a, b, c (x y z), a, (xx yy zz), x,

like image 587
hamdi Avatar asked Jul 26 '11 07:07

hamdi


3 Answers

This will work for a constant length of arguments with in the brackets.

REGEXP_REPLACE(t.col1, '(\(.*?),(.*?),(.*?\))', '\1\2\3') new_col

update inspired by @Kobi's comment:
this regular expression removes the 1st, optional 2nd and optional 3rd , between ()
it can be extended up to 9 (I've a book stating \1 ... \500 should be possible but only \1 ... \9 worked)

REGEXP_REPLACE(t.col1, '\(([^,]*),([^,]*),?([^,]*),?([^,]*)\)', '(\1\2\3\4)') new_col
like image 126
bw_üezi Avatar answered Oct 24 '22 10:10

bw_üezi


A little modified version of the regular expression you used:

REGEXP_REPLACE(column_name, '((\)|^).*?(\(|$))|,', '\1')
like image 2
Karolis Avatar answered Oct 24 '22 09:10

Karolis


Not sure if REGEXP_REPLACE supports negative look aheads and look behinds, but if it does this would work: ,(?<!\)[^\(]*)(?![^\)]*\()

I tested with C#:

string s = "a, b, c (x, y, z), a, (xx, yy, zz), x,";

Console.WriteLine(Regex.Replace(s, @",(?<!\)[^\(]*)(?![^\)]*\()", ""));
like image 1
Petar Ivanov Avatar answered Oct 24 '22 09:10

Petar Ivanov