0

I have a query that looks like this:

select regexp_replace('john (junior) jones','\([^)]*\)','','g');
  regexp_replace  
------------------
 john  jones

As you can see, this query removes the values in brackets but it results in a double space remaining.

Is there an easy way around this?

So far I have this, which works to an extent:

select regexp_replace((regexp_replace('john (junior) jones','\([^)]*\)','','g')),'\s','');
  regexp_replace  
------------------
 john jones

The above works but not when I pass through something like this:

select regexp_replace((regexp_replace('john (junior) jones (hughes) smith','\([^)]*\)','','g')),'\s','');
   regexp_replace    
---------------------
 john jones  smith

1 Answer 1

1
SELECT regexp_replace(
          'john (junior) jones (hughes) smith',
          ' *\([^)]*\) *',
          ' ',
          'g'
       );

  regexp_replace  
══════════════════
 john jones smith
(1 row)

To explain the regular expression:

  • an arbitrary number of spaces, followed by an opening parenthesis ( *\()
  • an arbitrary number of characters that are not a closing parenthesis ([^)]*)
  • a closing parenthesis and arbitrarily many spaces (\) *)

That is replaced with a single space.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! That is much closer to what I want - the only issue is if the brackets are at the start/end I am left with a trailing/leading space. Is it best to just wrap this up in a trim as a result?
Yes, perhaps that is a simpler solution than coming up with a more complicated expression.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.