PostgreSQL count number of times substring occurs in text

后端 未结 4 1863
名媛妹妹
名媛妹妹 2020-12-19 20:53

I\'m writing a PostgreSQL function to count the number of times a particular text substring occurs in another piece of text. For example, calling count(\'foobarbaz\', \'ba\'

相关标签:
4条回答
  • 2020-12-19 21:15

    I would highly suggest checking out this answer I posted to "How do you count the occurrences of an anchored string using PostgreSQL?". The chosen answer was shown to be massively slower than an adapted version of regexp_replace(). The overhead of creating the rows, and the running the aggregate is just simply too high.

    The fastest way to do this is as follows...

    SELECT
      (length(str) - length(replace(str, replacestr, '')) )::int
      / length(replacestr)
    FROM ( VALUES
      ('foobarbaz', 'ba')
    ) AS t(str, replacestr);
    

    Here we

    1. Take the length of the string, L1
    2. Subtract from L1 the length of the string with all of the replacements removed L2 to get L3 the difference in string length.
    3. Divide L3 by the length of the replacement to get the occurrences

    For comparison that's about five times faster than the method of using regexp_matches() which looks like this.

    SELECT count(*)
    FROM ( VALUES
      ('foobarbaz', 'ba')
    ) AS t(str, replacestr)
    CROSS JOIN LATERAL regexp_matches(str, replacestr, 'g');
    
    0 讨论(0)
  • 2020-12-19 21:28

    Try with:

    SELECT array_length (string_to_array ('1524215121518546516323203210856879', '1'), 1) - 1
    
    --RESULT: 7
    
    0 讨论(0)
  • 2020-12-19 21:32

    How about use a regular expression:

    SELECT count(*)
    FROM regexp_matches('foobarbaz', 'ba', 'g');
    

    The 'g' flag repeats multiple matches on a string (not just the first).

    0 讨论(0)
  • 2020-12-19 21:40

    There is a

    str_count( src,  occurence )
    

    function based on

    SELECT (length( str ) - length(replace( str, occurrence, '' ))) / length( occurence )
    

    and a

    str_countm( src, regexp )
    

    based on the @MikeT-mentioned

    SELECT count(*) FROM regexp_matches( str, regexp, 'g')
    

    available here: postgres-utils

    0 讨论(0)
提交回复
热议问题