Find multiple strings and replace with single string in Postgres

孤街浪徒 提交于 2019-12-08 10:17:26

问题


Is it possible to do a "find and replace" with the following?

UPDATE __table__ SET __column__ = replace(__column__, ' ', '_');

How do I define an array of strings to be found (',', ';', ':', ' ') to replace with '_'?


回答1:


Read the section about Bracket Expressions which explains how to search for characters within a string to replace

but this should work for you

UPDATE __table__ SET __column__ = regexp_replace( __column__, E'[\\s,;:]','_','g')



回答2:


regexp_replace() is powerful, versatile ... and slow.

If you can, use the plain (less powerful and versatile) replace(), which is much faster.

For the simple case at hand (replace a list of single characters with another single character) use translate() - even simpler and faster. And also much less error prone.

UPDATE tbl
SET    col =  translate(col, ',;: ', '____')
WHERE  col <> translate(col, ',;: ', '____'); -- avoid empty updates

Only update rows that actually change. It's a common (possibly expensive) mistake to update all rows unconditionally. Details:

  • How do I (or can I) SELECT DISTINCT on multiple columns?

Note that this only replaces the space character (' ') while the class shorthand \s in a regular expression matches all whitespace characters of the the character class [[:space:]].



来源:https://stackoverflow.com/questions/27691393/find-multiple-strings-and-replace-with-single-string-in-postgres

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!