sqlcmd.net validated sql reference
advanced string-processing MySQL MariaDB PostgreSQL

Extract A Substring Matching A Regular Expression

Return the portion of a string that matches a regular expression pattern, useful for parsing structured text without fixed delimiters.

Docker-validated Not currently validation-green

Extract the numeric error code from a log message string

The pattern [0-9]+ matches one or more consecutive digits. For 'Error code 4042 occurred' the first match is '4042'; for 'Warning 503 from gateway' it is '503'. PostgreSQL's REGEXP_MATCH returns a text array of capture groups; [1] retrieves the first element. MySQL and MariaDB return the matched substring directly. The SQL Server workaround locates the first digit with PATINDEX('%[0-9]%', ...), then extracts through the end of the digit run by finding where non-digits resume — correct for a single contiguous digit block but not a general regex engine.

MySQL MariaDB
Engine-specific syntax
Setup
CREATE TABLE logs (id INT, notes VARCHAR(200));

INSERT INTO
  logs (id, notes)
VALUES
  (1, 'Error code 4042 occurred'),
  (2, 'Warning 503 from gateway');
SQL
SELECT
  id,
  REGEXP_SUBSTR (notes, '[0-9]+') AS error_code
FROM
  logs
ORDER BY
  id;
iderror_code
14042
2503
PostgreSQL
Engine-specific syntax
Setup
CREATE TABLE logs (id INT, notes VARCHAR(200));

INSERT INTO
  logs (id, notes)
VALUES
  (1, 'Error code 4042 occurred'),
  (2, 'Warning 503 from gateway');
SQL
SELECT id, (REGEXP_MATCH(notes, '[0-9]+'))[1] AS error_code FROM logs ORDER BY id;
iderror_code
14042
2503

MySQL and MariaDB use REGEXP_SUBSTR(). PostgreSQL uses REGEXP_MATCH()[1]. SQL Server is unsupported natively; the workaround uses PATINDEX and SUBSTRING to extract the first contiguous digit sequence. All return the same string values.

Where this command helps.

  • extracting a phone number, email address, or code embedded in free-text log entries
  • pulling a numeric identifier from a string that mixes letters and numbers in variable positions

What the command is doing.

Regular expression extraction lets you pull variable-length substrings based on a pattern rather than fixed character positions. MySQL 8.0+ and MariaDB 10.0+ provide REGEXP_SUBSTR(string, pattern) which returns the first matching substring. PostgreSQL provides REGEXP_MATCH(string, pattern) which returns a text array; index [1] retrieves the first captured match. SQL Server has no built-in regular expression functions — pattern matching is limited to LIKE with wildcards. A CLR extension can add full regex support but is not available without explicit installation.