// strings reference

SQL REGEXP_SUBSTR function

Returns the substring that matches a regular expression, or NULL when the pattern does not match.

Категория
Strings
Returns
string or NULL
In this category
94 of 172

Синтаксис

REGEXP_SUBSTR(str, pattern [, start [, occurrence [, flags [, group]]]])

Поддержка движка

ДвижокSupportЗаметки
SQL Server Да SQL Server 2025 and Azure SQL Database.
PostgreSQL Да PostgreSQL 15+; older versions use SUBSTRING(str FROM pattern).
MySQL Да MySQL 8.0.4+; no capture-group argument.
SQLite Not built in No REGEXP_SUBSTR; extract in the application.
Oracle Да Supported under this name.

Примеры

Oracle

SELECT REGEXP_SUBSTR(path, '[^/]+', 1, 1) AS first_segment
FROM routes;

MySQL

SELECT REGEXP_SUBSTR('a1b22', '[0-9]+', 1, 2) AS second_number;  -- 22

Oracle

SELECT REGEXP_SUBSTR(email, '(.+)@(.+)', 1, 1, NULL, 2) AS domain
FROM users;

Полезно знать

  • A non-match returns NULL. In Oracle a zero-length match is NULL too, because Oracle treats the empty string as NULL.
  • The occurrence argument extracts later matches: occurrence 2 returns the second match, which is how you walk through repeated tokens.
  • The group argument (Oracle, PostgreSQL, SQL Server) picks a parenthesised group; 0, the default, is the whole match. MySQL has no group argument, so extracting a group there takes REGEXP_REPLACE with a backreference.

Questions about REGEXP_SUBSTR

How do I extract the second match of a pattern?

Pass occurrence 2: REGEXP_SUBSTR(str, pattern, 1, 2) starts at position 1 and returns the second match. Increase the occurrence to walk through the rest.

What is the PostgreSQL equivalent of REGEXP_SUBSTR?

PostgreSQL 15 added regexp_substr with the same arguments. On older versions SUBSTRING(str FROM pattern) returns the first parenthesised group, or the whole match when there are no groups, and regexp_match returns every group as an array.

Why does a successful extraction return NULL in Oracle?

Oracle stores the empty string as NULL. A pattern that matches zero characters, such as 'x*', yields NULL rather than an empty string.

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

// 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.