regex - Postgresql - 如何从字符串的末尾和没有结束数值的字符串中获取数值
问题描述
我在 Postgresql 用户表中有以下用户名。
**username**
test
123test
123test456
test123
test45test
test55test55
所以我试图分别获取没有结束数值和结束数值的字符串。
我期待以下输出
str num
----------------
test 0
123test 0
123test 456
test 123
test45test 0
test55test 55
如何编写将返回上述结果的 Postgresql 查询?
解决方案
你可以使用regexp_replace()
and substring()
:
select
regexp_replace(username, '\d+$', '') str,
coalesce(substring(username from '\d+$')::int, 0) num
from mytable
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
推荐阅读
- excel - 如何循环打印多页到一个pdf
- ios - Swift:从视图到警报视图或到另一个视图的语音转换
- java - 无法在 ubuntu 18.04 上启动 dbeaver
- angular - Angular firebase 托管 AT(...)firestore 不是一个函数
- windows - 当我尝试在 Windows 10 中启动项目时,Ionic 不起作用
- objective-c - 应用程序崩溃:发送到实例的选择器无法识别“
- kotlin - 在 Kotlin 对象成员中引用自己的类型
- c - 位图加载镜像和反转
- javascript - ESLint 未解析模块
- django - 如果条件满足,Django将对象保存到数据库