PostgreSQL – REGEX_REPLACE Function
The REGEXP_REPLACE
function is used to replace substrings within a string based on a regular expression pattern. It allows you to perform advanced pattern-based replacements on text data.
The syntax of the REGEXP_REPLACE
function is as follows:
REGEXP_REPLACE(string, pattern, replacement, flags)
where string
is the input string in which you want to perform replacements.
and pattern
is the regular expression pattern that defines the substring(s) you want to replace.
and replacement
is the string that will replace the matched substrings.
and flags
(optional): Flags that modify the behavior of the regular expression. These can include 'g'
(global) to replace all occurrences, 'i'
(case-insensitive), and others.
Here’s an example of how you might use the REGEXP_REPLACE
function in a SQL query:
SELECT REGEXP_REPLACE('Hello, World!', '[aeiou]', '*') AS modified_string;
In this example, the result would be the string 'H*ll*, W*rld!'
, as all vowels ('a'
, 'e'
, 'i'
, 'o'
, 'u'
) were replaced with an asterisk ('*'
) using the regular expression pattern [aeiou]
.
You can also use capturing groups in the pattern and refer to them in the replacement string:
SELECT REGEXP_REPLACE('John Doe (age: 30)', '(\w+) (\w+) \(age: (\d+)\)', '\3 years old \2 \1') AS modified_string;
In this case, the result would be '30 years old Doe John'
, as the regular expression pattern captured the first name, last name, and age, and then rearranged them in the replacement string.
The REGEXP_REPLACE
function is very powerful for advanced string manipulation tasks.