【问题标题】:Regular expression find and replace in PostgresPostgres中的正则表达式查找和替换
【发布时间】:2012-07-28 05:01:22
【问题描述】:

我有一个表,其中包含许多行,其中的列包含 URL。 URL 的格式为:

http://one.example1.com:9999/dotFile.com

我想用 http://example2.com/dotFile.com 替换该列中的所有匹配项,同时保留 :9999 之后的所有内容。我找到了一些关于 regexp_matches 和 regexp_replace 的文档,但我不能完全理解它。

【问题讨论】:

    标签: regex postgresql


    【解决方案1】:

    如果您知道网址,则不必使用正则表达式。 replace() 函数应该适合你:

    replace(string text, from text, to text)        
    Replace all occurrences in string of substring from with substring to   
    example: replace('abcdefabcdef', 'cd', 'XX')    abXXefabXXef
    

    你可以试试:

    UPDATE yourtable SET
      yourcolumn = replace(yourcolumn, 'one.example1.com:9999','example2.com')
    ;
    

    【讨论】:

    • 谢谢,成功了。更新表 SET field = replace(field, 'one.example1.com:9999','example2.com')
    • 这条评论是缺少的答案
    【解决方案2】:

    要替换固定字符串,请使用简单的replace() 函数。

    要替换动态字符串,您可以像这样使用regexp_replace()

    UPDATE
      YourTable
    SET
      TheColumn = regexp_replace(
        TheColumn, 'http://[^:\s]+:9999(\S+)', 'http://example2.com\1', 'g'
      )
    

    【讨论】:

    • replace() 在这里做了一个更简单的工作,正如您自己评论过的那样。但是,要将“所有匹配项”替换为regexp_replace(),您必须为“全局”添加第四个参数'g' ..。
    • @Erwin 感谢您的提示。我已经包括了。
    • 我正在寻找一个可以在 where 子句中使用的方法,例如 `UPDATE ... WHERE "email" = regexp_matches("email", E'.[co.tz]')`过滤并提高更新速度。但这也没关系,因为我只做一次,在开发中。谢谢,因为我真的很想要一个regexp 解决方案。 :)
    • 如果您的搜索字符串没有部分是可变的,那么使用正则表达式是没有意义的。由于正则表达式比基本字符串搜索慢得多,我会尽量避免使用它们。 “列的最后 5 个字符 = 'co.tz'”类型的搜索将比等效的正则表达式更快。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-25
    • 2011-06-16
    • 1970-01-01
    • 2017-01-28
    • 2015-01-11
    • 2012-12-02
    相关资源
    最近更新 更多