I’m not sure if this problem solvable with regular expressions (in Perl5 syntax), but here is self-explanatory example:
smth Y1 test X foo X Y2 bar X Y1 X X Y2
s/?/Z/g
smth Y1 test Z foo Z Y2 bar X Y1 Z Z Y2
Consider that Y1 always have a matching Y2 and there is no overlapping.
Here you go: