在postgresql中解析一个字符串

Parsing a string in postgresql

假设我有一个数据类型为 varchar 的列,该列包含与这些类似的值

'My unique id [john3 UID=123]'
'My unique id [henry2 UID=1234]'
'My unique id [tom2 UID=56]'
'My unique id [jerry25 UID=98765]'

如何使用 postgresql 只获取字符串中 UID= 之后的数字。 例如,在字符串 'My unique id [john3 UID=123]' 中,我只想要 123,类似地,在字符串 'My unique id [jerry25 UID=98765]' 中,我只想要 98765 PostgreSQL 有没有办法做到这一点?

我们可以在这里使用REGEXP_REPLACE

SELECT col, REGEXP_REPLACE(col, '.*\[\w+ UID=(\d+)\].*$', '') AS uid
FROM yourTable;

Demo

编辑:

如果给定值可能与上述模式不匹配,在这种情况下您想要 return 整个原始值,我们可以使用 CASE 表达式:

SELECT col,
       CASE WHEN col LIKE '%[%UID=%]%'
            THEN REGEXP_REPLACE(col, '.*\[\w+ UID=(\d+)\].*$', '')
            ELSE col END AS uid
FROM yourTable;

您还可以使用 regexp_matches 作为更短的正则表达式:

select regexp_matches(col, '(?<=UID\=)\d+') from t;