小编rya*_*uck的帖子

Postgres - 如果正则表达式匹配失败则返回默认值

我想尝试正则表达式匹配,null如果失败则返回。

以下查询尝试查找字符串中的第一个数字。结果会忽略带有 text 的条目'blah'。我更希望它返回一个null值。

这个问题可能与正则表达式无关,更多地与集合代数有关。我的预感是,有一种优雅的方法可以做到这一点,而不需要left join任何东西,尽管谷歌搜索被证明是徒劳的。

with test_data as (
  select 'abc 123' as txt
  union
  select 'abc 456' as txt
  union
  select 'blah' as txt
)

select
  txt,
  (regexp_matches(txt, '\d+'))[1] as first_num
from
  test_data
Run Code Online (Sandbox Code Playgroud)

postgresql pattern-matching functions set-returning-functions regex

3
推荐指数
1
解决办法
7561
查看次数