【问题标题】:Return numbers in string:postgresql返回字符串中的数字:postgresql
【发布时间】:2020-06-27 20:03:55
【问题描述】:

我有一个字符串:我今年 10 岁,有 500 个朋友。 我想返回 10 和 500,但是当我执行下面的查询时它返回空:

SELECT
REGEXP_MATCHES('I have the string: I am 10 years old with 500  friends',
                '-?\\d+','g');

【问题讨论】:

    标签: sql regex postgresql select


    【解决方案1】:

    问题在于双反斜杠。虽然有些数据库需要转义正则表达式字符类,但 Postgres 只需要一个反斜杠。

    所以:

    select regexp_matches(
        'I have the string: I am 10 years old with 500 friends',
        '-?\d+',
        'g'
    );
    

    '-?' 不适用于您的示例字符串。我保留它以防您想容纳可能的负数。

    Demo on DB Fiddle

    【讨论】:

      【解决方案2】:

      \\d 替换为[0-9]

      SELECT
        REGEXP_MATCHES(
          'I have the string: I am 10 years old with 500 friends',
          '(-?[0-9]+)','g'
        )
      

      输出:

      10
      500
      

      live demo

      【讨论】:

        猜你喜欢
        • 2015-12-02
        • 2020-07-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-09
        • 1970-01-01
        • 2021-12-30
        相关资源
        最近更新 更多