SQL REGEXP_SPLIT_TO_ARRAY function
Splits a string wherever a regular expression matches and returns the pieces as a text array.
- Categoria
- Strings
- Returns
text[]- In this category
- 107 of 172
Sintaxe
regexp_split_to_array(string, pattern [, flags])
Suporte a mecanismos
| Motor | Support | Notas |
|---|---|---|
| SQL Server | Not built in | No arrays; SQL Server 2025's REGEXP_SPLIT_TO_TABLE returns rows. |
| PostgreSQL | Sim | Supported under this name. |
| MySQL | Not built in | No regex split; JSON_TABLE or SUBSTRING_INDEX chains. |
| SQLite | Not built in | No regex split. |
| Oracle | Not built in | No direct equivalent; REGEXP_SUBSTR walks. |
Exemplos
PostgreSQL
SELECT regexp_split_to_array('a, b; c', '[,;][ ]*') AS parts; -- {a,b,c}
PostgreSQL
SELECT unnest(regexp_split_to_array(line, '\s+')) AS word FROM lines;
Bom saber
- The separator is a regex, so '[,;]\s*' splits on a comma or semicolon plus any following whitespace. With standard_conforming_strings on (the default), backslashes in a plain literal reach the regex engine unchanged.
- Zero-length matches split between characters: regexp_split_to_array('abc', 'x*') is {a,b,c}. Only zero-length matches at the very start or end, or right after a previous match, are ignored.
- A leading or trailing delimiter produces an empty first or last element: regexp_split_to_array(',a', ',') is {"",a}.
Questions about REGEXP_SPLIT_TO_ARRAY
When should I use string_to_array instead?
When the separator is a fixed string. string_to_array is faster and has no regex escaping to get wrong.
How do I split on any whitespace?
Use '\s+' or the POSIX class '[[:space:]]+', then unnest the array if you need rows.
Why does my array contain empty strings?
The input had adjacent delimiters or a delimiter at either end. Trim the string first, use a pattern with + so runs count as one separator, or filter empties after unnest.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: PostgreSQL.
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.