regexp_matches Extracts Capture Groups

Extract capture groups with regexp_matches, return every match with the g flag, and index the resulting text array.

SqlData Integrity

Code

snippet
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

FAQ

Which tables appear in this script?
`shipments` — referenced directly, no join needed.