Search code examples
pythonregexpython-re

Python re.sub How to replace every 0 in a string with a 2 when there is no 1 directly next to it?


I am completely new to regex and now I have the following task:

I have a string that looks like that: 001000X00X001X00X

Now i want to replace every 0 with a 2 when there is no 1 next to it that is not seperated by an X, so the example String should be changed to: 001000X22X001X22X

I tried to use something like this, to do that:

s = re.sub(r'X0+X', 'X2+X', s);

so it searches for substrings that begin and end with an X and have a random number of '0's between but obviously every substring like that is being changed to 'X2+X'. How can I count the number of 0s and replace every one of them with a 2?


Solution

  • I was too slow to provide a regex answer (@Wiktor Stribiżew, you're too fast!), so here is an alternative using the split string as intermediate:

    'X'.join([re.sub('0', '2', i) if not '1' in i else i for i in s.split('X')])
    

    If the string contains only 0/1/X, this would be a simpler/faster alternative:

    'X'.join(['2'*len(i) if not '1' in i else i for i in s.split('X')])
    

    NB. following @JvdV's comment, here is a fix of @WiktorStribiżew 's answer:

    re.sub(r'(?<=X)0+(?=X)', lambda x: '2'*len(x.group()), 'X'+s+'X')[1:-1]
    

    output: '22X001000X22X001X22X'