How get all matching positions in a string?

前端 未结 3 1892
轻奢々
轻奢々 2021-01-29 14:46

I have a column flag_acumu in a table in PostgreSQL with values like:

\'SSNSSNNNNNNNNNNNNNNNNNNNNNNNNNNNNSNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN\'         


        
3条回答
  •  难免孤独
    2021-01-29 15:25

    Since you didn't specify your needs to a point in which one could answer properly, I'm going with my assumption that you want a list of positions of occurence of a substring (can be more than 1 character long).

    Here's the function to do that using:

    • FOR .. LOOP control structure,
    • function substr(text, int, int).

    CREATE OR REPLACE FUNCTION get_all_positions_of_substring(text, text)
    RETURNS text
    STABLE
    STRICT
    LANGUAGE plpgsql
    AS $$
    DECLARE
      output_text TEXT := '';
    BEGIN
    
    FOR i IN 1..length($1)
    LOOP
      IF substr($1, i, length($2)) = $2 THEN
        output_text := CONCAT(output_text, ';', i);
      END IF;
    END LOOP;
    
    -- Remove first semicolon
    output_text := substr(output_text, 2, length(output_text));
    
    RETURN output_text;
    END;
    $$;
    

    Sample call and output

    postgres=# select * from get_all_positions_of_substring('soklesocmxsoso','so');
     get_all_positions_of_substring
    --------------------------------
     1;6;11;13
    

提交回复
热议问题