PostgreSQL 18 reference · String Functions

PostgreSQL REGEXP_COUNT() Function

Count how many times a regular expression matches in a string. Added in PostgreSQL 15.

PostgreSQL 18 Since 15

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

regexp_count(string, pattern, start, flags)

Parameters

ParameterDescription
string The input text.
pattern A POSIX regular expression.
start optional The character to start from. Default: 1
flags optional For example i.

Return value

An integer.

Examples

Count matches
SELECT regexp_count('banana', 'an') AS an, regexp_count('Hello World', '[aeiou]', 1, 'i') AS vowels;

Output

 an | vowels
----+--------
  2 |      3
(1 row)

Run this on your computer — see “Get Started” for setup.

Count words
SELECT name, regexp_count(name, '\s') + 1 AS words
FROM products
LIMIT 3;

Output

           name           | words
--------------------------+-------
 SQL for Beginners        |     3
 Clean Code               |     2
 The Pragmatic Programmer |     3
(3 rows)

Run this on your computer — see “Get Started” for setup.

Version history

VersionChange
PostgreSQL 15Added

Was this page helpful?