【问题标题】:How to get the more than one mached keywords using regexp_matches如何使用 regexp_matches 获取多个匹配的关键字
【发布时间】:2021-02-10 16:34:34
【问题描述】:

如何在给定的字符串中获取多个匹配的关键字。 请查找以下查询。

 SELECT regexp_matches(UPPER('bakerybaking'),'BAKERY|BAKING');

输出:“{BAKERY}”

上述场景给定的字符串与两个关键字匹配。 当我执行上述查询时,只得到一个关键字。 如何获取其他匹配的关键字。

【问题讨论】:

    标签: regex postgresql


    【解决方案1】:

    g是在regex中使用的全局搜索标志。用于获取所有匹配的字符串

    select regexp_matches(UPPER('bakerybaking'),'BAKERY|BAKING','g')
    
    
    
    regexp_matches 
    text[]
    -------------- 
    {BAKERY}       
    {BAKING}  
    

    将结果作为单行获取:

    SELECT ARRAY(select array_to_string(regexp_matches(UPPER('bakerybaking'),'BAKERY|BAKING','g'),''));
    
    array 
    text[]          
    --------------- 
    {BAKERY,BAKING} 
    

    通过使用unnest - 将返回的数组转换为表格

    select unnest(regexp_matches(UPPER('bakerybaking'),'BAKERY|BAKING','g'))
    
    unnest 
    text
    ------ 
    BAKERY 
    BAKING 
    

    【讨论】:

      【解决方案2】:

      根据:http://www.postgresql.org/docs/9.5/static/functions-string.html

      SELECT regexp_matches(UPPER('bakerybaking'),'(BAKERY)(BAKING)');
      

      输出:)

      regexp_matches ----------------- {BAKERY,BAKING}(1 行)

      【讨论】:

      【解决方案3】:

      哦,人类。请谢谢我。

      --https://stackoverflow.com/questions/52178844/get-second-match-from-regexp-matches-results
      --https://stackoverflow.com/questions/24274394/postgresql-8-2-how-to-get-a-string-representation-of-any-array
      CREATE OR REPLACE FUNCTION aaa(anyarray,Integer, text)
      RETURNS SETOF text
      LANGUAGE plpgsql
      AS $function$
      DECLARE s $1%type;
      BEGIN
      FOREACH s SLICE 1 IN ARRAY $1[$2:$2] LOOP
      RETURN NEXT array_to_string(s,$3);
      END LOOP;
      RETURN;
      END;
      $function$;
      
      --SELECT aaa((ARRAY(SELECT unnest(regexp_matches('=If(If(E_Reports_@ >=1, DMT(E_Date_R1_@, DateShift),0)', '(\w+_@)|([0-9]+)','g'))::TEXT)),1,',')
      --select (array[1,2,3,4,5,6])[2:5];
      SELECT aaa(array_remove(Array(SELECT unnest(regexp_matches('=If(If(E_Reports_@ >=1, DMT(E_Date_R1_@, DateShift),0)', '(\w+_@)|([0-9]+)','g'))::TEXT), Null),3,',')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-09
        • 1970-01-01
        相关资源
        最近更新 更多