1

I want to convert a string ___abc_[_]xyz to ...abc.\_xyz using regular expression.

Is it possible to convert _ and [_] into . and \_ respectively in the same query?

This is what I have done so far:

SELECT regexp_replace('___abc_[_]xyz','\[(.)\]','\\\1','g');

and

SELECT regexp_replace('___abc_[_]xyz','\[_\]','\_','g');

The Result of both queries is: ___abc_\_xyz

1
  • Since you are trying to replace with a hardcoded text, it is not possible without a callback, but PostgreSQL regexp functions do not accept callback functions as replacement arguments. Commented Sep 4, 2018 at 13:07

2 Answers 2

1

A douible regexp_replace can do the job:

SELECT regexp_replace(regexp_replace('___abc_[_]xyz','(?!\[)_(?!\])','.','g'),'\[_\]','\\_','g');
 regexp_replace 
----------------
 ...abc.\_xyz
(1 row)

The first one, using (?!\[)_(?!\]) will replace underscore NOT in between [ & ] with a dot.

The second will replace [_] with \_

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

Comments

1

You can do this with a triple replace:

SELECT replace(replace(replace('___abc_[_]xyz','[_]','***MYREPLACE***'),'_','.'),'***MYREPLACE***','\_');
  1. you replace all [_] by a special string that can't exist in your string and not containing _ ( in my example ***MYREPLACE***)

  2. you replace all _ by .

  3. you replace all ***MYREPLACE*** by \_

1 Comment

I like this solution best because it is much simpler and faster than using a regular 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.