首页 > 解决方案 > PostgreSQL regex_replace

问题描述

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

标签: regexpostgresql

解决方案


双重 regexp_replace 可以完成这项工作:

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

第一个, using将用点替换&(?!\[)_(?!\])之间的下划线 NOT 。[]

第二个将替换[_]\_


推荐阅读