single PCRE regex to swap ‘0’ for ‘1’ and ‘1’ for ‘0’ at a specific location in a string

My input string has either a ‘0’ or a ‘1’ at a specific location.
If it’s a ‘1’, I want to replace it with ‘0’ and likewise if it’s ‘0’ replace it with a ‘1’.

Working on the assumption ‘x’ will never occur and my string is just a single character, I can do it with 3 regexes like so:

s/0/x/
s/1/0/
s/x/0/

but that’s pretty messy. I was wondering if PCRE has something fancy that can do this with just one expression?


Source: regex

Leave a Reply