【问题标题】:How to extract only 5 digit number from a string using REGEXP sql如何使用 REGEXP sql 从字符串中仅提取 5 位数字
【发布时间】:2017-01-06 19:43:34
【问题描述】:

我只需要在 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

【问题讨论】:

    标签: sql amazon-redshift


    【解决方案1】:

    使用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:]]|$)')
    

    【讨论】:

    • 我收到ERROR: 42883: function regexp_matches("unknown", "unknown") does not exist
    • 你使用的是哪个版本的 postgres?
    • 我使用 redshift db... REGEXP_REPLACE 有效,但不是这个
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-03
    • 2021-01-08
    • 2021-04-20
    • 1970-01-01
    • 1970-01-01
    • 2021-07-18
    相关资源
    最近更新 更多