正则表达式删除字符串中所有出现的多个字符 [英] Regex remove all occurrences of multiple characters in a string
问题描述
在我的PostgreSQL中,我想替换字符串中所有(;<>)
出现的字符。
In my PostgreSQL I want to replace all characters (;<>)
occurrences in a string.
我的查询:
update table_name set text = regexp_replace(text, '/[(;<>)]+/g', '');
我认为我的正则表达式是错误的。有人可以帮我解决这个问题吗?
I think my regexp is wrong. Can anyone help me out with it?
推荐答案
使用更快的 translate()
:
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');
基本元素是第四个参数'g'
取代全局,而不仅仅是第一个匹配项。第二个参数是字符类。
您在正确的位置上,只是 regexp_replace()。
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().
如果您不希望更改所有行,我强烈建议您修改 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, '(;<>)', '');
这样您可以避免(昂贵的)空更新。 (在这种情况下会自动覆盖 NULL
。)
This way you avoid (expensive) empty updates. (NULL
is covered automatically in this particular case.)
这篇关于正则表达式删除字符串中所有出现的多个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!