Tabular IQ
Back to Function Index

REGEXP_EXTRACT()

Overview

REGEXP_EXTRACT() returns the first part of a string that matches a regular expression. Given a group number, it returns only what that pair of parentheses in the pattern matched, which is the usual way to pull one piece out of a value: the digits of an invoice number, the domain of an email address, the year in a reference. When nothing matches, the result is an empty string.

Function Format

REGEXP_EXTRACT(string, pattern [, group [, options]])

Return Value

REGEXP_EXTRACT() returns a character string

Examples


// The first match
REGEXP_EXTRACT('foo123bar456', '[0-9]+') = '123'

// A group number: what that pair of parentheses matched
REGEXP_EXTRACT('a12b34', '([a-z])([0-9]+)', 1) = 'a'
REGEXP_EXTRACT('a12b34', '([a-z])([0-9]+)', 2) = '12'

// Group 0 is the whole match
REGEXP_EXTRACT('a12b34', '([a-z])([0-9]+)', 0) = 'a12'

// Nothing matches: an empty string
REGEXP_EXTRACT('abc', '[0-9]+') = ''

// +? takes as little as it can
REGEXP_EXTRACT('<a><b>', '<.+?>') = '<a>'
REGEXP_EXTRACT('<a><b>', '<.+>') = '<a><b>'

// Ignoring case
REGEXP_EXTRACT('ABC', '(b)', 1, 'i') = 'B'

Notes

  • The group is written as a number from 0 to 9. Groups are counted by their opening parenthesis, from 1; group 0, or no group at all, is the whole match.
  • The result is an empty string, not a null, when nothing matches, when the pattern has no group of that number, and when the group took no part in the match.
  • Only the first match is read. A pattern can step over an earlier occurrence to reach a later one: '[0-9]+[^0-9]+([0-9]+)' with group 1 is the second number in a string.
  • Matching is case-sensitive. (?i) at the start of the pattern ignores case, and so does 'i' as the fourth argument, after the group number.
  • \d, \w and \s stand for a digit, a letter, digit or underscore, and a blank, of the unaccented alphabet.
  • A pattern that is not valid is refused, with the reason, when the formula is checked.
  • If the string or the pattern is null, the result is null.

See Also