By default, in PostgreSQL, regexp_replace()
replaces the first occurrence of a substring in a string, while replace()
replaces all occurrences of a substring in a string. Why is the default behavior different?
(I know that with regexp_replace
one can use the g
option to replace all occurrences of a substring in a string.)
Examples:
SELECT regexp_replace('hello world', 'o', 'z'); -- returns "hellz world"
SELECT regexp_replace('hello world', 'o', 'z', 'g'); -- returns "hellz wzrld"
SELECT replace('hello world', 'o', 'z'); -- returns: "hellz wzrld"
Best Answer
Why?
Because Postgres
replace()
is a standard SQL function that works the same as in other RDBMS. Example:replace()
in SQL Server:While
regexp_replace()
is used to ...The handling of regular expressions is obviously guided by the POSIX standard and works the same as other tools implementing it. The manual: