繁体   English   中英

如何在 postgresql 中使用 REGEXP_REPLACE 查找和替换字符串

[英]How to find and replace string using REGEXP_REPLACE in postgresql

我有一张 email 地址表:

CREATE TABLE contacts(
    email     VARCHAR(255)
)

INSERT INTO contacts VALUES    
    ('example.person@gmail.com'),
    ('example.person2@gmail.com'),
    ('example.person3@gmail.com');

如何找到并替换 email 格式,所以example.person@gmail.com -> example.person_gmailcom@test.com

例如:

UPDATE contacts
SET email = REGEXP_REPLACE(email, '@', '@test.com');

结果在example.person@test.comgmail.com

这里的游乐场: https://dbfiddle.uk/GnIfomiO

这可能是最简单的方法,方法是将 email 地址在@上一分为二,保留它之前的部分并替换. 在它之后的部分一无所有。 然后你可以只 append @test.com得到结果:

UPDATE contacts
SET email = SPLIT_PART(email, '@', 1) || '_' || REPLACE(SPLIT_PART(email, '@', 2), '.', '') || '@test.com';

Output 用于您的演示:

email
example.person_gmailcom@test.com
example.person2_gmailcom@test.com
example.person3_gmailcom@test.com

dbfiddle 上的演示

演示: https://dbfiddle.uk/0KWPVeAI

UPDATE contacts
SET email = REGEXP_REPLACE(email, '@', '_gmailcom@');

UPDATE contacts
SET email = REGEXP_REPLACE(email, '@.*$', '@test.com');

正则表达式模式是@ 跟随所有字符到字符串结尾

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM