// strings reference

SQL REGEXP_COUNT function

Counts the non-overlapping matches of a regular expression inside a string.

类别
Strings
Returns
integer
In this category
95 of 172

语法

REGEXP_COUNT(str, pattern [, start [, flags]])

引擎支持

引擎Support备注
SQL Server 是 SQL Server 2025 and Azure SQL Database.
PostgreSQL 是 PostgreSQL 15 and later.
MySQL Not built in No REGEXP_COUNT; for a literal, (CHAR_LENGTH(s) - CHAR_LENGTH(REPLACE(s, x, ''))) / CHAR_LENGTH(x).
SQLite Not built in No REGEXP_COUNT.
Oracle 是 Supported under this name.

示例

Oracle

SELECT REGEXP_COUNT(log_line, 'error', 1, 'i') AS errors
FROM logs;

PostgreSQL

SELECT regexp_count('a1b22c333', '[0-9]+') AS numbers;  -- 3

值得了解

  • Matches do not overlap: REGEXP_COUNT('aaa', 'aa') is 1, because the first match consumes two characters and the scan continues after it.
  • Returns 0 when the pattern never matches and NULL when the string is NULL; wrap in COALESCE before summing counts across rows.
  • Before PostgreSQL 15 the workaround is counting rows: (SELECT count(*) FROM regexp_matches(str, pattern, 'g')).

Questions about REGEXP_COUNT

How do I count occurrences of a literal substring instead of a regex?

Compare lengths: (LENGTH(s) - LENGTH(REPLACE(s, 'ab', ''))) / LENGTH('ab'). It works in every engine; in SQL Server use DATALENGTH or LEN with care, since LEN ignores trailing spaces.

Does REGEXP_COUNT count overlapping matches?

No. 'aa' in 'aaa' counts once. Counting overlaps needs a lookahead pattern such as '(?=aa)' where the engine supports it (PostgreSQL does, SQL Server's RE2 does not) or a manual walk.

What is the PostgreSQL equivalent?

regexp_count(str, pattern) from PostgreSQL 15. On older versions, count the rows of regexp_matches(str, pattern, 'g').

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, Oracle.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.