【问题标题】:How do I use regular expressions in PostgreSQL to remove the end of a field matching pattern?如何在 PostgreSQL 中使用正则表达式来删除字段匹配模式的结尾?
【发布时间】:2014-08-25 16:44:44
【问题描述】:

如何简化这个 PostgreSQL?基本上我想检查字段是否以 (1) 或只是 (1) 并从 1-30 的数字替换和重复。我认为它可以以某种方式使用正则表达式来完成,但我还没有让它工作。

UPDATE discogs.artist_meta
SET name = substr(name,0, strpos(name,' (1)'))
WHERE name LIKE '% (1)';

UPDATE discogs.artist_meta
SET name = substr(name,0, strpos(name,'(1)'))
WHERE name LIKE '%(1)';


UPDATE discogs.artist_meta
SET name = substr(name,0, strpos(name,' (2)'))
WHERE name LIKE '% (2)';

UPDATE discogs.artist_meta
SET name = substr(name,0, strpos(name,'(2)'))
WHERE name LIKE '%(2)';

【问题讨论】:

    标签: sql regex postgresql


    【解决方案1】:
    1. 使用regexp_replace(target, regexp, replacewith)function
    2. 您的模式类似于' ?\(([1-9]|[12][0-9]|30)\)$'
    3. 我不确定您要替换什么...只是删除号码?如果是,请替换为''

    正则表达式解释:

    " ?"                 = optional space
    \(                   = opening parenthesis (escaped)
    ([1-9]|[12][0-9]|30) = numbers 1-30
    \)                   = closing parenthesis (escaped)
    $                    = end of content
    

    关于您的评论:

    update discogs.artist_meta
    set name = regexp_replace(name, ' ?\(([1-9]|[12][0-9]|30)\)$', '')
    where name ~ ' ?\(([1-9]|[12][0-9]|30)\)$'
    

    【讨论】:

    • 我认为你不需要那个$。这将缩短正则表达式。行尾前还需要 1-2 个字符
    • 我可以在 LIKE 上应用它吗?我只想更改包含所述正则表达式的行
    猜你喜欢
    • 2011-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多