Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using postgres regexp_replace to replace a list of strings by always the same string

Tags:

Hi i would like to use regexp_replace (or any other postgres function if reasonable) to replace characters in a string by a '', i.e. erase them.

Using regexp_replace(('def4abcdef4ab','4', '','g') i can replace/erase all occurrences of '4', but i want to also replace all occurences of 'e' and b' in the same process, without using several nested processes like regexp_replace(regexp_replace(regexp_replace())).

i.e. i want to be able to provide a short list of different strings which then should be replace by a unique string.

Any ideas? Thanks a lot in advance!

like image 535
sal Avatar asked Oct 24 '13 08:10

sal


People also ask

Can you use regex to replace string?

RegEx makes replace ing strings in JavaScript more effective, powerful, and fun. You're not only restricted to exact characters but patterns and multiple replacements at once.

Can you use regex in PostgreSQL?

The simplest use of regex in PostgreSQL is the ~ operator, and its cousin the ~* operator. value ~ regex tests the value on the left against the regex on the right and returns true if the regex can match within the value. Note that the regex does not have to fully match the whole value, it just has to match a part.

How does regex replace work?

The REGEXREPLACE( ) function uses a regular expression to find matching patterns in data, and replaces any matching values with a new string. standardizes spacing in character data by replacing one or more spaces between text characters with a single space.


2 Answers

The canonical way is to use character classes, like so,

regexp_replace('def4abcdef4ab','[4eb]', '','g') 

though @alexius's method can also handle strings.

Not sure if perhaps non-greedily quantifying the expression would make it more efficient, e.g. [4eb]+?.

like image 176
slackwing Avatar answered Sep 21 '22 10:09

slackwing


regexp_replace('def4abcdef4ab','4|e|b', '','g')

like image 22
alexius Avatar answered Sep 24 '22 10:09

alexius