Updated on 2026-11-06 GMT+08:00

regexp_replace

The regexp_replace function replaces substrings in source that match pattern with the specified string replacement and returns the result string. Spark 4.0 supports the position parameter, which allows specifying the match occurrence from which to start replacing.

Syntax

regexp_replace(str, pattern, replacement[, position]) 

Parameters

Table 1 Parameter descriptions

Parameter

Mandatory

Type

Description

str

Yes

STRING

The string to be replaced.

pattern

Yes

STRING

The regular expression pattern. An error is returned if pattern is an empty string.

replacement

Yes

STRING

The string to replace the substrings matching pattern.

position

No

BIGINT

Specifies to replace all matches starting from the position-th match. If 0 or 1, all matches are replaced. If another type or less than 0, an error is returned. The default value is 0 (replace all matches).

Return Values

Returns a value of type STRING.

  • If pattern is an empty string, an error is reported.
  • When a non-existent group is referenced, no replacement is performed.
  • If replacement is NULL and pattern has a match, NULL is returned.
  • If str, pattern, or position is NULL, NULL is returned.

Example Code

Replace all matches. Return num-num.

SELECT regexp_replace('100-200', '(\\d+)', 'num'); 

Replace all matches. Return 2222.

SELECT regexp_replace('abcd', '[a-z]', '2'); 

Start replacing from the 2nd match. Return a222.

SELECT regexp_replace('abcd', '[a-z]', '2', 2); 

Start replacing from the 3rd match. Return ab22.

SELECT regexp_replace('abcd', '[a-z]', '2', 3); 

Start replacing from the 4th match. Return abc2.

SELECT regexp_replace('abcd', '[a-z]', '2', 4);