首页 > 解决方案 > Postgresql - 如何从字符串的末尾和没有结束数值的字符串中获取数值

问题描述

我在 Postgresql 用户表中有以下用户名。

**username**
test
123test
123test456
test123
test45test
test55test55

所以我试图分别获取没有结束数值和结束数值的字符串。

我期待以下输出

str          num
----------------
test         0
123test      0
123test      456
test         123
test45test   0
test55test   55

如何编写将返回上述结果的 Postgresql 查询?

标签: regexstringpostgresqltrimnumeric

解决方案


你可以使用regexp_replace()and substring()

select
    regexp_replace(username, '\d+$', '') str,
    coalesce(substring(username from '\d+$')::int, 0) num
from mytable

DB Fiddlde 上的演示

with mytable as (
    select 'test' username
    union all select '123test'
    union all select '123test456'
    union all select 'test123'
    union all select 'test45test'
    union all select 'test55test55'
)
select
    regexp_replace(username, '\d+$', '') str,
    coalesce(substring(username from '\d+$')::int, 0) num
from mytable
字符串 | 数
:--------- | --:
测试 | 0
123测试 | 0
123测试 | 456
测试 | 123
测试45测试 | 0
测试55测试 | 55

推荐阅读