Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle: counting the number of substrings in a string?

Tags:

oracle

plsql

How do I count the number of occurrences of a substring inside of a string?

like image 747
Mark Harrison Avatar asked Mar 17 '23 14:03

Mark Harrison


2 Answers

As of version 11g, regexp_count will do this.

select regexp_count('abba', 'b') from dual;
   2 
select regexp_count('abba', 'b+') from dual;
   1 
like image 98
Mark Harrison Avatar answered Mar 20 '23 12:03

Mark Harrison


In pre-11g version you can:

select (length(string) - length(replace(string,substring,''))) / length(substring) as occ
from dual;

The idea is to see how much space in the string is occupied by the substring, then, to see how many times the substring is in that space just divide to the length of substring.

like image 35
Florin stands with Ukraine Avatar answered Mar 20 '23 12:03

Florin stands with Ukraine