REGEXP_REPLACE()
Overview
The REGEXP_REPLACE()
function replaces all occurrences of a regular expression pattern in a string with a specified replacement string.
Syntax
The syntax for REGEXP_REPLACE()
function is as follows:
Parameters
source_string
: string that we want to perform the replacement onpattern
: POSIX regular expression pattern to matchreplacement
: replacement stringflags
: (optional) string that changes the matching behavior ofREGEXP_REPLACE()
function
The flags
parameter is an optional string that controls how the function operates. Here is a list of flags supported in Oxla:
g
: global replacement. This flag ensures that all occurrences of the pattern are replacedi
: use this flag for case-insensitive matchingc
:REGEXP_REPLACE()
function is case sensitive by default, using thec
flag has the same effect as using no flags
Examples
Basic function usage
In this example, we will focus on using REGEXP_REPLACE()
function with a basic POSIX regular expression pattern:
By executing the query above, we will get the following output:
The pattern used was “T[^ ]*”, which matches any substring that starts with a ‘T’ character, followed by any number of non-space characters. The function replaces the matched substring with the specified replacement string “We”.
Replacing special characters
This example demonstrates how to replace a non-alphanumeric character in a string with a tilde (~):
In the above query, the second parameter is a regular expression “[^A-Za-z0-9 ]” that matches any characters that are not uppercase / lowercase letters, digits or spaces. The output for executing the query above will be as follows:
Flags usage
Replacing certain substrings with a single flag defined
This example will focus on using the REGEXP_REPLACE()
function with a defined flag and replacing certain substrings in a string. For the needs of this section, we will create a sample quotes
table:
By executing the code above, we will get the following output:
Now, we will use the REGEXP_REPLACE()
function with the i
flag specifiec to replace all occurrences of the word lazy
with active
regardless of the case sensitivity:
In this case, all occurrences of the word lazy
have been replaced with active
:
Specifying one or more flags
Without specifying the g
flag, REGEXP_REPLACE()
function replaces only the first occurrence of a substring:
In this case, as you can see only the first digit (1
) was replaced with X
. By adding the g
flag, all occurrences are replaced with X
:
ci
flags, the regex will be case-insensitive, while using the ic
flags it will be case-sensitiveRestrictions
- The function returns
NULL
if there are no input rows orNULL
values - If the regular expression pattern isn’t found in the string, the
REGEXP_REPLACE()
function returns the original string i
andc
flags shouldn’t be used with each other