regexp_matches Extracts Capture Groups
Extract capture groups with regexp_matches, return every match with the g flag, and index the resulting text array.
Code
CREATE TABLE shipments (
id int PRIMARY KEY,
reference text NOT NULL
);
INSERT INTO shipments (id, reference)
VALUES
(1, 'order-2024-0042'),
(2, 'order-2025-0117'),
(3, 'return-2024-0009');
SELECT reference,
regexp_matches(reference, 'order-([0-9]{4})-([0-9]+)') AS parts
FROM shipments
WHERE reference LIKE 'order-%';
-- The g flag returns one row per match instead of one row per input.
SELECT regexp_matches('a1 b2 c3', '[a-z]([0-9])', 'g') AS digit;
-- Index into the returned text array to read a single capture group.
SELECT (regexp_matches('order-2024-0042', 'order-([0-9]{4})-([0-9]+)'))[1] AS year,
(regexp_matches('order-2024-0042', 'order-([0-9]{4})-([0-9]+)'))[2] AS sequence;What the code does
What runs here is SELECT / INSERT / CREATE — shipments are the objects involved.
Breaking the statements into their working parts: a WHERE clause narrowing which rows one statement affects; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Applying it
Run the statement against the shipments table.
Statements that matter
SELECT reference,
regexp_matches(reference, 'order-([0-9]{4})-([0-9]+)') AS parts
FROM shipments
WHERE reference LIKE 'order-%';
SELECT (regexp_matches('order-2024-0042', 'order-([0-9]{4})-([0-9]+)'))[1] AS year,
(regexp_matches('order-2024-0042', 'order-([0-9]{4})-([0-9]+)'))[2] AS sequence;
INSERT INTO shipments (id, reference)
VALUES
(1, 'order-2024-0042'),
(2, 'order-2025-0117'),
(3, 'return-2024-0009');
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.DSN Connection String ParserParse PostgreSQL, MySQL, Redis, MongoDB, and AMQP DSN URLs locally with masked credentials, multi-host support, default ports, and SSL/pool inspection.
FAQ
- Which tables appear in this script?
- `shipments` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.