问题
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:
- use the
regexp_replace(target, regexp, replacewith)function - your pattern would be something like
' ?\(([1-9]|[12][0-9]|30)\)$' - 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