Tabular IQ
Back to Function Index

REGEXP_REPLACE()

Overview

REGEXP_REPLACE() replaces the part of a string that matches a regular expression. It replaces the first match; with 'g' as the fourth argument it replaces every match, which is what cleaning a value usually calls for: stripping everything but the digits from a phone number, squeezing runs of spaces in a name. The replacement can reuse what the pattern matched, so the parts of a value can be reordered or wrapped.

Function Format

REGEXP_REPLACE(string, pattern, replace string [, options])

Return Value

REGEXP_REPLACE() returns a character string

Examples


// The first match, or every match with 'g'
REGEXP_REPLACE('a1b22c', '[0-9]+', '#') = 'a#b22c'
REGEXP_REPLACE('a1b22c', '[0-9]+', '#', 'g') = 'a#b#c'

// Squeezing runs of spaces
REGEXP_REPLACE('  hamilton   foods  ', ' +', ' ', 'g') = ' hamilton foods '

// \1 to \9 stand for what the numbered parentheses matched
REGEXP_REPLACE('a1b23c', '([0-9])([0-9])', '\2\1') = 'a1b32c'
REGEXP_REPLACE('abc', '([a-z])', '<\1>', 'g') = '<a><b><c>'

// \0 stands for the whole match
REGEXP_REPLACE('abc', 'b', '[\0]') = 'a[b]c'

// Ignoring case
REGEXP_REPLACE('ABC', 'b', 'x', 'i') = 'AxC'
REGEXP_REPLACE('aAa', 'a', 'x', 'gi') = 'xxx'

Notes

  • Without 'g' only the first match is replaced. This differs from REPLACE(), which replaces every occurrence of its search string.
  • In the replace string, \1 to \9 stand for what the numbered pair of parentheses matched, \0 for the whole match, and two backslashes for one backslash. A dollar sign has no special meaning.
  • A replace string that names a group the pattern does not have leaves the string as it is.
  • The option letters can be combined: 'gi' replaces every match and ignores case. (?i) at the start of the pattern also ignores case, and 's' lets a dot match a line break.
  • \d, \w and \s stand for a digit, a letter, digit or underscore, and a blank, of the unaccented alphabet. An accented letter counts as one character.
  • A pattern that is not valid is refused, with the reason, when the formula is checked.
  • If the string, the pattern or the replace string is null, the result is null.

See Also