I have written a regex for matching the sub string with spaces around it but that's not working well

Viewed 34

Actually I was working on a regex problem whose task is to take a substring (||, &&) and replaces it with another substring (or, and) and I wrote code for it but that's not working well

question = x&& &&& && && x || | ||\|| x
Expected output = x&& &&& and and x or | ||\|| x

Here is the code I wrote

import re
for i in range(int(input())):
    print(re.sub(r'\s[&]{2}\s', ' and ', re.sub(r"\s[\|]{2}\s", " or ", input())))

My output = x&& &&& and && x or | ||\|| x

3 Answers

You need to use lookarounds, the problem with the current regex is && && here the && the first match captures the space so there's no space available before the second && and it won't match, so we need to use zero-length-match ( lookarounds)

Replace the regex

\s[&]{2}\s  -->  (?<=\s)[&]{2}(?=\s)
\s[\|]{2}\s -->    (?<=\s)[\|]{2}(?=\s)

(?<=\s) - Match should be precede space characters

(?=\s) - Match should be followed by space characters

You're looking for a regex like (?<=\s)&&(?=\s) (Regex demo)

Using lookarounds to assert the position of space characters around your targeted replacement groups allows overlapping matches to occur - otherwise, it will match the spaces on both sides and block out the other options.

import re

in_str = 'x&& &&& && && x || | ||\|| x'
expect_str = 'x&& &&& and and x or | ||\|| x'

print(re.sub("(?<=\s)\|\|(?=\s)", "or", re.sub("(?<=\s)&&(?=\s)", "and", in_str)))

Python demo

Try using re.findall() instead of re.sub

Related