使用 Postgres regexp_replace 从字符串中删除所有不在提供列表中的字符
Using Postgres regexp_replace to erase all characters that are not in a provided list from a string
如何从字符串中删除所有不在提供的字符列表中的字符?
例如:"valid" 个字符的列表是 2,n,w,s
要处理的字符串是'24nQ/m'
,结果应该是'2n'
您可以使用 regex_replace
将任何其他字符替换为空字符串:
SELECT *,
regexp_replace(col, '[^2nws]','','g') AS replaced
FROM tab;
输出:
╔═══════════╦══════════╗
║ col ║ replaced ║
╠═══════════╬══════════╣
║ 24nQ/m ║ 2n ║
║ 2444nQ/m ║ 2n ║
║ aaa ║ ║
║ Nn ║ n ║
╚═══════════╩══════════╝
如果您想忽略大小写,请使用 'gi'
标志。
另一种方法是使用translate
函数:
SELECT *,
translate(col, translate(col, '2nws','^'),'') AS replaced
FROM tab;
如何从字符串中删除所有不在提供的字符列表中的字符?
例如:"valid" 个字符的列表是 2,n,w,s
要处理的字符串是'24nQ/m'
,结果应该是'2n'
您可以使用 regex_replace
将任何其他字符替换为空字符串:
SELECT *,
regexp_replace(col, '[^2nws]','','g') AS replaced
FROM tab;
输出:
╔═══════════╦══════════╗
║ col ║ replaced ║
╠═══════════╬══════════╣
║ 24nQ/m ║ 2n ║
║ 2444nQ/m ║ 2n ║
║ aaa ║ ║
║ Nn ║ n ║
╚═══════════╩══════════╝
如果您想忽略大小写,请使用 'gi'
标志。
另一种方法是使用translate
函数:
SELECT *,
translate(col, translate(col, '2nws','^'),'') AS replaced
FROM tab;