regexregex-greedynon-greedy

replace a string, starting last occurrence of of a character


In this string:

a=b&c=blablabla_[OO]

I'm trying to replace everything between the "=" sign and the "[OO]"

I've tried:

/(=.+?)_\[OO\]

but this replaces starting the first "=" sign detected instead of the last (closest to [OO]).

How can I achieve this?

Thanks!


Solution

  • You could make use of either 2 capturing groups or lookarounds combined with a negated character class [^=]+ matching 1+ times any char except an equals sign:

    (=)[^=]+(\[OO\])
    

    Regex demo

    In the replacement use the 2 capturing groups $1REPLACEMENT$2


    With lookarounds (if supported)

    (?<==)[^=]+(?=\[OO\])
    

    Regex demo