How do I use regular expressions in PostgreSQL to remove the end of a field matching pattern?

给你一囗甜甜゛ 提交于 2021-01-29 04:52:21

问题


How can I simplify this PostgreSQL? Basically I want to check if the fields end with (1) or just (1) and replace and repeat from numbers from 1-30. I assume it can be done with regular expressions somehow, but I haven't got it working.

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:


  1. use the regexp_replace(target, regexp, replacewith) function
  2. your pattern would be something like ' ?\(([1-9]|[12][0-9]|30)\)$'
  3. i'm not exactly sure what you are trying to replace with...just removing the number? if so, replace with ''.

Regexp explanation:

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

Regarding your comment:

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


来源:https://stackoverflow.com/questions/25490567/how-do-i-use-regular-expressions-in-postgresql-to-remove-the-end-of-a-field-matc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!