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.
Related on SQLly
- Extract leading digits from a string in SQL Snippet
- Extract trailing digits from a string in SQL Snippet
- Split a comma-separated field into rows in SQL Snippet
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, Oracle.
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.