Skip to content

Regular expression functions: REGEXP, REGEXP_LIKE, REGEXP_REPLACE, REGEXP_SUBSTR

View as Markdown

CoraDB matches strings against regular expressions with the REGEXP (or RLIKE) operator and five functions:

Function Returns
REGEXP, RLIKE 1 if the pattern matches anywhere in the string, otherwise 0
REGEXP_LIKE Same as REGEXP, as a function with a match type
REGEXP_COUNT The number of matches
REGEXP_INSTR The position of a match
REGEXP_SUBSTR The text of a match
REGEXP_REPLACE The string with matches replaced

Matching is case-insensitive by default. Use REGEXP BINARY, or the match type 'c' of the functions, for case-sensitive matching.

Patterns follow the ECMAScript (JavaScript) regular expression grammar, implemented with the C++ <regex> library. Matching is done on characters, not bytes, so patterns work on multibyte UTF-8 text.

Backslashes in patterns reach the regular expression engine unchanged as long as the no_backslash_escapes parameter is yes (the default): write '\d+', not '\\d+'.

Characters Matches
. Any character except line terminators (LF, CR, LS, PS)
\t, \n, \v, \f, \r Tab, Line feed, Vertical tab, Form feed, Carriage return
\cletter The control character whose code is the code of letter modulo 32
\xhh, \uhhhh The character with the hexadecimal code hh or hhhh
\0 The null character
\num Back-reference: the text matched by group num
\d, \D A decimal digit ([[:digit:]]), any other character
\s, \S A whitespace character ([[:space:]]), any other character
\w, \W A letter, digit or underscore ([_[:alnum:]]), any other character
\character The character itself. Escape ^ $ \ . * + ? ( ) [ ] { } | to match them literally
[class], [^class] A character in (or not in) the character class
SELECT ('coradb dbms' REGEXP '^c.*$'), REGEXP_COUNT('a1 b22 c333', '\d+'), REGEXP_REPLACE('hello coradb world', '\b(\w)\w*', '$1');
('coradb dbms' REGEXP '^c.*$') REGEXP_COUNT('a1 b22 c333', '\d+') REGEXP_REPLACE('hello coradb world', '\b(\w)\w*', '$1')
1 3 h c w
Quantifier The preceding item is matched
* 0 or more times
+ 1 or more times
? 0 or 1 time
{n} Exactly n times
{n,} n or more times
{min,max} Between min and max times
SELECT ('Aaaapricot' REGEXP '^A+pricot'), ('Apricot' REGEXP '^Aa?pricot'), ('Aaapricot' REGEXP '^Aa?pricot'), ('coracora' REGEXP '^(cora)*$'), ('coradb' REGEXP '^(cora)*$');
('Aaaapricot' REGEXP '^A+pricot') ('Apricot' REGEXP '^Aa?pricot') ('Aaapricot' REGEXP '^Aa?pricot') ('coracora' REGEXP '^(cora)*$') ('coradb' REGEXP '^(cora)*$')
1 1 0 1 0

Quantifiers are greedy: they take as many characters as possible. Add ? after a quantifier to make it lazy (as few as possible):

SELECT REGEXP_SUBSTR('aardvark', '(a+)'), REGEXP_SUBSTR('aardvark', '(a+?)');
REGEXP_SUBSTR('aardvark', '(a+)') REGEXP_SUBSTR('aardvark', '(a+?)')
aa a
Syntax Meaning
(subpattern) Group that captures the matched text
(?:subpattern) Group that does not capture

Captured groups are numbered by the position of their opening parenthesis. In the pattern, \1, \2, ... refer back to them; in the replacement string of REGEXP_REPLACE, use $1, $2, ...

SELECT REGEXP_REPLACE('hello coradb', '([[:alnum:]]+)', '$1!');
REGEXP_REPLACE('hello coradb', '([[:alnum:]]+)', '$1!')
hello! coradb!

The group ([a-c]{3}) captures abc, and \1 requires the same three letters again:

SELECT REGEXP_SUBSTR('abckabcjabc', '([a-c]{3})k\1j\1');
REGEXP_SUBSTR('abckabcjabc', '([a-c]{3})k\1j\1')
abckabcjabc

Assertions test a position without consuming characters.

Syntax True at a position
^ At the start of the string (or after a line terminator)
$ At the end of the string (or before a line terminator)
\b Between a word character and a non-word character
\B Not at a word boundary
(?=subpattern) Followed by subpattern (positive lookahead)
(?!subpattern) Not followed by subpattern (negative lookahead)
SELECT REGEXP_REPLACE('coradb dbms coradb sql coradb rdbms', 'coradb(?= sql)', 'CoraDB'), REGEXP_REPLACE('coradb dbms coradb sql coradb rdbms', 'coradb(?! sql)', 'CoraDB');
REGEXP_REPLACE('coradb dbms coradb sql coradb rdbms', 'coradb(?= sql)', 'CoraDB') REGEXP_REPLACE('coradb dbms coradb sql coradb rdbms', 'coradb(?! sql)', 'CoraDB')
coradb dbms CoraDB sql coradb rdbms CoraDB dbms coradb sql CoraDB rdbms

| separates alternatives. The pattern matches if any alternative matches; inside a group, | separates alternatives of the group only.

SELECT ('a' REGEXP 'a|b'), ('d' REGEXP 'a|b'), ('c' REGEXP 'a|b|c');
('a' REGEXP 'a|b') ('d' REGEXP 'a|b') ('c' REGEXP 'a|b|c')
1 0 1

A class in square brackets matches one character: a list of characters ([abc]), a range ([a-f], [0-9]), a named class ([[:digit:]]), or any mix of them. [^...] matches any character not in the class.

Named class Characters
[:alnum:] Letters and digits
[:alpha:] Letters
[:blank:] Space and tab
[:cntrl:] Control characters
[:digit:], [:d:] Decimal digits
[:graph:] Characters with a visible representation
[:lower:] Lowercase letters
[:print:] Printable characters
[:punct:] Punctuation
[:space:], [:s:] Whitespace
[:upper:] Uppercase letters
[:xdigit:] Hexadecimal digits
[:w:] Word characters (letters, digits, underscore)

A named class is only valid inside a bracket expression: [[:alpha:]] matches a letter, but [:alpha:] is a plain list of the characters :, a, l, p and h.

SELECT ('d' REGEXP '[abc]'), ('adf' REGEXP '[a-f]'), ('strike' REGEXP '^[^a-dXYZ]+$'), REGEXP_SUBSTR('aas200gjb', '[0-9]+'), REGEXP_REPLACE('Côte de Blaye', '[[:alpha:]]+', '#');
('d' REGEXP '[abc]') ('adf' REGEXP '[a-f]') ('strike' REGEXP '^[^a-dXYZ]+$') REGEXP_SUBSTR('aas200gjb', '[0-9]+') REGEXP_REPLACE('Côte de Blaye', '[[:alpha:]]+', '#')
0 1 1 200 # # #

[[:alpha:]] matches accented letters such as ô too, so Côte is replaced as one word.

expression REGEXP [BINARY] pattern
expression RLIKE [BINARY] pattern
expression NOT REGEXP [BINARY] pattern

Returns 1 if pattern matches any part of expression, 0 if it does not, and NULL if the pattern is NULL. REGEXP and RLIKE are synonyms. Matching is case-insensitive; with BINARY it is case-sensitive.

Unlike LIKE, which must match the whole value, REGEXP succeeds when the pattern matches anywhere. Anchor the pattern with ^ and $ to match the whole value.

SELECT ('ABC' REGEXP 'abc'), ('Tourtière' RLIKE 'tourti.re'), ('Tourtière' NOT REGEXP 'tourti.re');
('ABC' REGEXP 'abc') ('Tourtière' RLIKE 'tourti.re') ('Tourtière' NOT REGEXP 'tourti.re')
1 1 0

All product names start with a capital letter. A case-insensitive match finds the names that start with A, B or C; with BINARY, the lowercase class [a-c] matches none of them:

SELECT COUNT(DISTINCT name) FROM product WHERE name REGEXP '^[a-c]';
COUNT(DISTINCT name)
56
SELECT COUNT(DISTINCT name) FROM product WHERE name REGEXP BINARY '^[a-c]';
COUNT(DISTINCT name)
0

Product names that contain characters outside printable ASCII (the range from space to ~):

SELECT name FROM product WHERE name REGEXP '[^ -~]' ORDER BY name;
name
Côte de Blaye
Guaraná Fantástica
Original Frankfurter Grüne Soße
Pâte chinois
Thüringer Rostbratwurst
Tourtière
REGEXP_LIKE (string, pattern [, match_type])

Returns 1 if pattern matches any part of string, otherwise 0. It is the function form of REGEXP.

  • match_type: 'i' for case-insensitive matching (the default) or 'c' for case-sensitive matching. Any other value is an error.

If any argument is NULL, the result is NULL. An empty pattern matches nothing. Return type: INT

SELECT REGEXP_LIKE('abbbbc', 'ab+c'), REGEXP_LIKE('abbbbc', 'AB+C'), REGEXP_LIKE('abbbbc', 'AB+C', 'c'), REGEXP_LIKE('abbbbc', '');
REGEXP_LIKE('abbbbc', 'ab+c') REGEXP_LIKE('abbbbc', 'AB+C') REGEXP_LIKE('abbbbc', 'AB+C', 'c') REGEXP_LIKE('abbbbc', '')
1 1 0 0

The customer phone numbers are stored in several formats. REGEXP_LIKE finds the ones written as (nnn)nnn-nnnn:

SELECT id, phone, REGEXP_LIKE(phone, '^[(][0-9]{3}[)][0-9]{3}-[0-9]{4}$') AS us_format
FROM customer WHERE id < 6 ORDER BY id;
id phone us_format
0 001-800-310-4977 0
1 122-213-1333 0
2 7443494058 0
3 +1-435-097-0394 0
4 (352)927-2666 1
5 (461)755-7077 1
REGEXP_COUNT (string, pattern [, position [, match_type]])

Returns the number of times pattern matches in string.

  • position: the character position where the search starts (default 1). Zero or a negative value is an error.
  • match_type: 'i' (default) or 'c', as for REGEXP_LIKE.

If any argument is NULL, the result is NULL. An empty pattern returns 0. Return type: INT

From position 3, the case-insensitive search finds A, b, a, A and A; the case-sensitive search finds only b and a:

SELECT REGEXP_COUNT('ab123Ab111aAA', '[a-d]', 3), REGEXP_COUNT('ab123Ab111aAA', '[a-d]', 3, 'c');
REGEXP_COUNT('ab123Ab111aAA', '[a-d]', 3) REGEXP_COUNT('ab123Ab111aAA', '[a-d]', 3, 'c')
5 2
REGEXP_INSTR (string, pattern [, position [, occurrence [, return_option [, match_type]]]])

Returns the position of a match of pattern in string, or 0 if there is none.

  • position: where the search starts (default 1). Zero or a negative value is an error.
  • occurrence: which match to return (default 1).
  • return_option: 0 (default) returns the position of the first character of the match; 1 returns the position of the character after the match.
  • match_type: 'i' (default) or 'c'.

If any argument is NULL, the result is NULL. Positions are counted in characters. Return type: INT

SELECT REGEXP_INSTR('12354abc5', '[[:alpha:]]+', 1, 1, 0), REGEXP_INSTR('12354abc5', '[[:alpha:]]+', 1, 1, 1), REGEXP_INSTR('12345abcdeabcde', '[a-c]+', 1, 2);
REGEXP_INSTR('12354abc5', '[[:alpha:]]+', 1, 1, 0) REGEXP_INSTR('12354abc5', '[[:alpha:]]+', 1, 1, 1) REGEXP_INSTR('12345abcdeabcde', '[a-c]+', 1, 2)
6 9 11

The position of the first non-ASCII character in product names, and how many there are:

SELECT name, REGEXP_INSTR(name, '[^ -~]') AS first_non_ascii, REGEXP_COUNT(name, '[^ -~]') AS non_ascii
FROM product WHERE name REGEXP '[^ -~]' ORDER BY name;
name first_non_ascii non_ascii
Côte de Blaye 2 1
Guaraná Fantástica 7 2
Original Frankfurter Grüne Soße 24 2
Pâte chinois 2 1
Thüringer Rostbratwurst 3 1
Tourtière 7 1
REGEXP_REPLACE (string, pattern, replacement [, position [, occurrence [, match_type]]])

Returns string with the matches of pattern replaced by replacement. In replacement, $1, $2, ... insert the text captured by groups.

  • position: where the search starts (default 1). Zero or a negative value is an error.
  • occurrence: 0 (default) replaces every match; n replaces only the n-th match.
  • match_type: 'i' (default) or 'c'.

If any argument is NULL, the result is NULL. An empty pattern leaves the string unchanged. Return type: STRING

SELECT REGEXP_REPLACE('12345abDEKBcde', '[a-d]', '#'), REGEXP_REPLACE('12345abDEKBcde', '[a-d]', '#', 1, 0, 'c'), REGEXP_REPLACE('12345abcdeabcde', '[a-d]', '#', 1, 2);
REGEXP_REPLACE('12345abDEKBcde', '[a-d]', '#') REGEXP_REPLACE('12345abDEKBcde', '[a-d]', '#', 1, 0, 'c') REGEXP_REPLACE('12345abcdeabcde', '[a-d]', '#', 1, 2)
12345###EK###e 12345##DEKB##e 12345a#cdeabcde

Normalizing the customer phone numbers to digits only:

SELECT id, phone, REGEXP_REPLACE(phone, '[^0-9]', '') AS digits FROM customer WHERE id < 6 ORDER BY id;
id phone digits
0 001-800-310-4977 0018003104977
1 122-213-1333 1222131333
2 7443494058 7443494058
3 +1-435-097-0394 14350970394
4 (352)927-2666 3529272666
5 (461)755-7077 4617557077
REGEXP_SUBSTR (string, pattern [, position [, occurrence [, match_type]]])

Returns the text of a match of pattern in string, or NULL if there is none.

  • position: where the search starts (default 1). Zero or a negative value is an error.
  • occurrence: which match to return (default 1).
  • match_type: 'i' (default) or 'c'.

If any argument is NULL, the result is NULL. An empty pattern returns NULL. Return type: STRING

SELECT REGEXP_SUBSTR('aas200gjb', '[0-9]+');
REGEXP_SUBSTR('aas200gjb', '[0-9]+')
200
SELECT REGEXP_SUBSTR('12345abcdeabcde', '[k-z]+');
REGEXP_SUBSTR('12345abcdeabcde', '[k-z]+')
NULL

The second comma-separated part of each customer address is the city:

SELECT id, address, REGEXP_SUBSTR(address, '[^,]+', 1, 2) AS city FROM customer WHERE id < 4 ORDER BY id;
id address city
0 725 French Centers,Jonathanburgh, KY 91607 Jonathanburgh
1 687 Griffin Estates,Bowmanton, NV 36334 Bowmanton
2 454 Lisa Ramp Suite 214,North Charlesborough, VA 84416 North Charlesborough
3 7023 Mcintosh Parkways,Scottfort, MS 56742 Scottfort

The customer addresses end with a two-letter state code and a five-digit ZIP code. A lookahead extracts the state, and the case-sensitive match type keeps lowercase words out:

SELECT id, REGEXP_SUBSTR(address, '[0-9]{5}$') AS zip, REGEXP_SUBSTR(address, '[A-Z]{2}(?= [0-9]{5}$)', 1, 1, 'c') AS state
FROM customer WHERE id < 6 ORDER BY id;
id zip state
0 91607 KY
1 36334 NV
2 84416 VA
3 56742 MS
4 13968 AE
5 11468 WY