OTARIKI OTARIKI - 2 years ago 58
SQL Question

regexp_replace replace every piece in text

I have string like this:


I need replace this piece
with this:
but only when they are between
tags. result must be:


I am trying this:

select regexp_replace('aa/ss/[img]aa/ss/dd[/img][img]aa/ss/dd[/img]aa/ss', '(\[img\].*/)ss(/.*\[\/img\])', '\1WW\2', 'g')

But this replaces just one piece, not both. I use
flag buth same result.

How to do this correctly ?

Answer Source

The problem is the "greediness" of the operators. You have repeated expressions so either ss could match the pattern once or twice -- depending on whether the middle '[/img][img] is counted as the match to the .* or to the fixed pattern.

Unfortunately, it is easier for me to diagnose the problem than fix it -- I find greediness in regular expressions to simply be confusing. But, here is a fix for your particular string. It just takes the '[' character into account:

select regexp_replace('aa/ss/[img]aa/ss/dd[/img][img]aa/ss/dd[/img]aa/ss',
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download