代码之家  ›  专栏  ›  技术社区  ›  Setu Kumar Basak

如何知道SQL查询中匹配了哪种正则表达式模式

  •  0
  • Setu Kumar Basak  · 技术社区  · 4 年前

    我正在写一个SQL查询,我已经 n 要在查询中匹配的正则表达式。

    SELECT * FROM
    Sample_Table
    WHERE
    (REGEXP_CONTAINS(content, r"[a-z0-9A-Z]{40}") OR -- expression 1
    REGEXP_CONTAINS(content, r"[0-9a-z]{32}") OR -- expression 2
    ..................
    REGEXP_CONTAINS(content, r"[a-z0-9]{80}") OR -- expression n-1
    REGEXP_CONTAINS(content, r"[a-z0-9A-Z\%]{35}")) -- expression n 
    

    现在,当我返回结果时,我想知道特定的返回行是由表达式1或表达式2匹配的。一种选择是运行每个正则表达式一次并标记结果。但是,由于Google BigQuery中的资源限制,我不得不在一个查询中运行所有正则表达式。

    有没有办法用匹配的正则表达式标记每个返回的结果行?

    1 回复  |  直到 4 年前
        1
  •  2
  •   Mikhail Berlyant    4 年前

    考虑以下方法

    with patterns as (
      select 1 pattern_id, r"[a-z0-9A-Z]{40}" pattern union all
      select 2, r"[0-9a-z]{32}" union all
      select 3, r"[a-z0-9]{80}" union all
      select 4, r"[a-z0-9A-Z\%]{35}"
    )
    select any_value(t).*, string_agg('' || pattern_id) matches  
    from Sample_Table t, patterns p
    where regexp_contains(content, pattern)
    group by format('%t', t)     
    

    如果您有更好的列可用于 group by 你应该使用它——例如

    select any_value(t.sample_repo_name), string_agg('' || pattern_id) as matches  
    from `bigquery-public-data.github_repos.sample_contents` t, patterns p
    where regexp_contains(content, pattern)
    group by id