gpt4 book ai didi

sql - 如何使用REGEXP sql从字符串中仅提取5位数字

转载 作者:行者123 更新时间:2023-12-01 13:39:27 25 4
gpt4 key购买 nike

我只需要在 postgresql 或 redshift DB 中使用 REGEXP sql 从字符串中提取 5 位数字

例如,

f 34 123 54321 123456

上面的字符串应该返回
54321

我只能从字符串中获取数字,而不仅仅是 5 位数字
select REGEXP_REPLACE('f 34 123 54321 123456', '[^0-9]') five_digit_number
--returns 3412354321123456

最佳答案

使用 regexp_matches

select regexp_matches('f 34 123 54321 123456','\y\d{5}\y','g')

指定 'g' 标志将为您提供所有匹配项,以防字符串中出现多于一个 5 位数字。
\y 指定字边界。

对于 Redshift,您可以使用 regexp_substr
select REGEXP_SUBSTR('f 34 123 54321 123456', '(^|[^[:word:]]|[[:space:]])\\d{5}([^[:word:]]|[[:space:]]|$)')

关于sql - 如何使用REGEXP sql从字符串中仅提取5位数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41513156/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com