2

In my PostgreSQL I want to replace all characters (;<>) occurrences in a string.

My query:

update table_name set text = regexp_replace(text, '/[(;<>)]+/g', '');

I think my regexp is wrong. Can anyone help me out with it?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
faya
  • 5,535
  • 11
  • 37
  • 49

1 Answers1

7

Use the much faster translate() for this simple case:

UPDATE tbl SET text = translate(text, '(;<>)', '');

Every character in the second parameter that has no counterpart in the third parameter is replaced with nothing.

The regular expression solution could look like this:

regexp_replace(text, '[(;<>)]', '', 'g');

Essential element is the 4th parameter 'g' to replace "globally" instead of just the first match. The second parameter is a character class.
You were on the right track, just a matter of syntax for regexp_replace().

Hint on UPDATE

If you don't expect all rows to be changed, I would strongly advise to adapt your UPDATE statement:

UPDATE tbl
SET    text =  translate(text, '(;<>)', '')
WHERE  text <> translate(text, '(;<>)', '');

This way you avoid (expensive) empty updates. (NULL is covered automatically in this particular case.)

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
  • Awesome. Yes, that is exactly what I wanted to achieve. Thank you! – faya Feb 19 '13 at 08:55
  • Actually, the OP's regex pattern is correct (it does have /g flag), it should just have been written a bit different in Postgres. Anyway, very good point regarding `translate`. – raina77ow Feb 19 '13 at 08:57
  • @raina77ow: Yes, just a matter of syntax for the regular expression. I added the parenthesis to my example, seems the OP wants to replace those, too. – Erwin Brandstetter Feb 19 '13 at 09:15