如何在PostgreSQL中使用正则表达式来删除字段匹配模式的结尾?

时间:2014-08-25 16:44:45

标签: sql regex postgresql

如何简化这个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)';

1 个答案:

答案 0 :(得分:2)

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

    " ?"                 = 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)\)$'