Counting the number of occurrences of a substring within a string in PostgreSQL

后端 未结 5 970
南旧
南旧 2020-12-03 09:49

How can I count the number of occurrences of a substring within a string in PostgreSQL?


Example:

I have a table

CREATE TABLE test.\"use         


        
相关标签:
5条回答
  • 2020-12-03 10:05
    Occcurence_Count = LENGTH(REPLACE(string_to_search,string_to_find,'~'))-LENGTH(REPLACE(string_to_search,string_to_find,''))
    

    This solution is a bit cleaner than many that I have seen, especially with no divisor. You can turn this into a function or use within a Select.
    No variables required. I use tilde as a replacement character, but any character that is not in the dataset will work.

    0 讨论(0)
  • Other way:

    UPDATE test."user" SET result = length(regexp_replace(name, '[^o]', '', 'g'));
    
    0 讨论(0)
  • 2020-12-03 10:12

    A common solution is based on this logic: replace the search string with an empty string and divide the difference between old and new length by the length of the search string

    (CHAR_LENGTH(name) - CHAR_LENGTH(REPLACE(name, 'substring', ''))) 
    / CHAR_LENGTH('substring')
    

    Hence:

    UPDATE test."user"
    SET result = 
        (CHAR_LENGTH(name) - CHAR_LENGTH(REPLACE(name, 'o', ''))) 
        / CHAR_LENGTH('o');
    
    0 讨论(0)
  • 2020-12-03 10:24

    A Postgres'y way of doing this converts the string to an array and counts the length of the array (and then subtracts 1):

    select array_length(string_to_array(name, 'o'), 1) - 1
    

    Note that this works with longer substrings as well.

    Hence:

    update test."user"
        set result = array_length(string_to_array(name, 'o'), 1) - 1;
    
    0 讨论(0)
  • 2020-12-03 10:24

    Return count of character,

     SELECT (LENGTH('1.1.1.1') - LENGTH(REPLACE('1.1.1.1','.',''))) AS count
    --RETURN COUNT OF CHARACTER '.'
    
    0 讨论(0)
提交回复
热议问题