PostgreSQL regexp_match() Function

The PostgreSQL regexp_match() function returns the first match of the specified regular expression from a string.

The regexp_match() function uses POSIX regular expressions.

regexp_match() Syntax

This is the syntax of the PostgreSQL regexp_match() function:

regexp_match(string, regex[, flags])  text[]

Parameters

string

Required. The string to search in.

regex

Required. The regular expression.

flags

Optional. The matching mode of the regular expression.

Return value

The PostgreSQL regexp_match() function returns an array of strings that are the result of the first match in a string using the specified regular expression.

If there is no match of the specified regular expression in the string, this function returns null.

If the regular expression contains groups, then each match of groups becomes an element of the result array.

You cannot use the g flag in the regexp_match() function, otherwise an error will be raised: “ERROR: regexp_match() does not support ‘global’ option Hint: use regexp_matches function instead”.

regexp_match() Examples

This example shows how to use the regexp_match() function to return a result captured by a regular expression from a string:

SELECT regexp_match('Abcd abCd aBcd', 'ab.');
 regexp_match
--------------
 {abC}

Here, . matchs any character in POSIX regular expressions.

You can use the flag i in the parameter flags to perform an insensitive-case matching. For example:

SELECT regexp_match('Abcd abCd aBcd', 'ab.', 'i');
 regexp_match
--------------
 {Abc}

You can use multiple groups in regular expressions like:

SELECT regexp_match('Abcd abCd aBcd', '(a.)(c.)', 'i');
 regexp_match
--------------
 {Ab,cd}