代码之家  ›  专栏  ›  技术社区  ›  Andrus

如何在sql中查找第二个匹配项

  •  0
  • Andrus  · 技术社区  · 3 周前

    查询

    select (regexp_matches('Main fabric: 50% Organic Cotton, 49% Cotton, 1% Elastane', '\b(\d+)%'))[2]
    

    不返回任何行。

    正则表达式测试 https://regex101.com/r/nVP3Wg/1 按预期返回3行。

    如何获取第二匹配值?

    使用Postgres 16

    2 回复  |  直到 3 周前
        1
  •  1
  •   Stefanov.sm    3 周前

    使用 regexp_matches 功能与 with ordinality g 旗帜。

    select r[1] second_match 
    from regexp_matches('Main fabric: 50% Organic Cotton, 49% Cotton, 1% Elastane', 
                        '\y(\d+)%',
                        'g'
      ) with ordinality as t(r, o)
    where o = 2;
    

    (以及 \y 锚元字符而不是 \b )

        2
  •  0
  •   malyshchyk    3 周前

    使用这里描述的g标志来获取所有匹配项,而不仅仅是第一个: https://www.postgresql.org/docs/current/functions-matching.html

    我还认为返回值是数组数组,所以尝试像[1][2]那样访问以获得第二个匹配项

        3
  •  0
  •   Zegarek    3 周前

    您可以使用 regexp_substr() :
    demo at db<>fiddle

    select regexp_substr('Main fabric: 50% Organic Cotton, 49% Cotton, 1% Elastane', 
                        '\y(\d+)%',1,2,'',1)
    
    regexp_substr
    49

    图案后的其他参数:

    • 1 告诉从头开始
    • 2 意味着你想要第二场比赛
    • '' 在那里你可以添加旗帜,比如 'i' 用于不区分大小写的匹配
    • 1. 表示模式中的第一个括号子表达式-您需要数字,而不需要 %