概述
前段时间迁移oracle 11g数据至pg 9.6,应用用到了oracle函数regexp_count,在此分享在pg中实现此函数的方法
1.REGEXP_COUNT函数语法参考
REGEXP_COUNT (source_char, pattern [, position [, match_param]])
2.使用示例:
1)得到字符串中小写字母“a”的出现次数 (大小写敏感)
sys@ora11g> select regexp_count ('The pro-niece was born today, so exciting.', 'a') "Count 'a'" from dual;
Count 'a'
----------
2
sys@ora11g> select regexp_count ('THE PRO-NIECE WAS BORN TODAY, SO EXCITING!', 'a') "Count 'a'" from dual;
Count 'a'
----------
0
3、pg 9.6中实现regexp_count函数
[postgre@host132 project1]$ psql -Upostgres
psql (9.6.12)
Type "help" for help.
postgres=# create or replace function regexp_count(text, text)
postgres-# returns integer language sql as $$
postgres$# select count(m)::int
postgres$# from regexp_matches($1, $2, 'g') m
postgres$# $$;
CREATE FUNCTION
postgres=#
测试:
postgres=# select regexp_count('abcdabc','a');
regexp_count
--------------
2
(1 row)
postgres=# select regexp_count('abcdabc','A');
regexp_count
--------------
0
(1 row)
postgres=#