Home > front end >  replace comma within brackets
replace comma within brackets

Time:10-06

I have the below text and I am trying to replace the commas inside the brackets alone.

[alpha ,beta, theta01, zeta01], [x9001, A2201, zeta01] The intended output is

[alpha beta theta01 zeta01], [x9001 A2201 zeta01] I am trying to accomplish this using the regular expression

WITH t AS (SELECT '[alpha, beta,theta01,zeta01], [x9001, A2201, zeta01]' col1 
             )
SELECT t.col1
     ,REGEXP_REPLACE(t.col1, "(\\[[A-Za-z0-9]*)*,", "\\1") new_col
  FROM t;

\[ -- escaped character [ \1 -- escaped group pattern

however, the comma between the brackets is also getting removed. here is the output I am getting

[alpha beta theta01 zeta01] [x9001 A2201 zeta01] <----<>

Any pointers would be appreciated.

CodePudding user response:

Consider below approach

select col1,
  ( select string_agg(regexp_replace(el, ',', ''), ', ')
    from unnest(regexp_extract_all(col1, r'\[.*?\]')) el
  ) new_col
from t      

if applied to sample data in your question - output is

enter image description here

  • Related