I would like to find a regex that would replace %%
with %
and %s
with my custom string foobar
. This is tricker that it sounds, because it should turn %%s
into %s
and not %foobar
, so this naive implementation does not work:
s/%%/%/g
s/%s/foobar/g
This problem is quite common and I've come across it multiple times in my programming life. Not just percent s or percent escaping, but also backslash character or backlash escaping. I'm going to post my usual solution but I'm wondering if there's a better way.
(Allow me to do some keyword stuffing for my future searches: character pairs, backslash backslash, backslash x, percent percent, percent s. Thank you.)
If there are specific language features that would help in this use-case, I'd be interested in hearing what they are.
Example input and output:
input : test %%, test %s, test %%s too
output : test %, test foobar, test %s too
Another one:
input : test%%,test%s,test%%stoo
output : test%,testfoobar,test%stoo