Using PostgreSQL, how can I replace all forward slashes by a hyphen after 5 occurrences of a forward slash like so:
https://this/is/a/very/long/url
to this :
https://this/is/a/very-long-url
Using PostgreSQL, how can I replace all forward slashes by a hyphen after 5 occurrences of a forward slash like so:
https://this/is/a/very/long/url
to this :
https://this/is/a/very-long-url
2
Answers
You can combine
regexp_replace()
withregexp_instr()
. The latter tells you where’s the 6th forward slash/
, the former starts at that position and continues replacements until the end of the string: demoYou could probably reduce this to just the
regexp_replace()
if you change the pattern to include groups of anything followed by a/
, and tell it to replace just the slash, keeping the rest, from the 6th group onward.A single
regexp_replace()
with a smart pattern does it:fiddle
url
can be any string, not necessarily an URL. Every slash (/
) after the first 5 is replaced with a hyphen (-
).The regular expression explained:
(?<=re)
.. positive lookbehind (match only after this expression).*?
.. ‘.’ matches any character,*?
is the non-greedy quantifier "0-n times, as few as possible"{5}
.. quantifier for the preceding atom1
.. in the replacement is a back reference to the captured match.'g'
.. The final parameter ‘g’ stands for "globally", i.e. replace all matches, not just the first one.