3

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"
Erwin Brandstetter
186k28 gold badges463 silver badges636 bronze badges
asked Apr 2, 2016 at 2:28
2
  • If the default of regexp_replace is same as replace, replace is not needed. Additionally, g option is the same behavior of Unix tools that operate regular expressions such as sed. Commented Apr 3, 2016 at 1:34
  • 1
    I took the liberty to fix the twisted bit about replace() in question. Now it should make sense. Commented Apr 4, 2016 at 0:33

1 Answer 1

7

Why?

Because Postgres replace() is a standard SQL function that works the same as in other RDBMS. Example: replace() in SQL Server:

Replaces all occurrences of a specified string value with another string value.

While regexp_replace() is used to ...

Replace substring(s) matching a POSIX regular expression.

The handling of regular expressions is obviously guided by the POSIX standard and works the same as other tools implementing it. The manual:

POSIX regular expressions provide a more powerful means for pattern matching than the LIKE and SIMILAR TO operators. Many Unix tools such as egrep, sed, or awk use a pattern matching language that is similar to the one described here.

answered Apr 3, 2016 at 23:12

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.