4

I want to replace all occurrences of && with and.

For example, x&& && && should become x&& and and.

I tried re.sub(' && ', ' and ', 'x&& && && '), but it didn't work, the first && already consumed the whitespace so the second one didn't match.

Then I thought of non-capturing group and tried but failed again.

How can I solve this problem?

3 Answers 3

3

You could use non-word boundaries here.

>>> re.sub(r'\B&&\B', 'and', 'x&& && &&')
'x&& and and'
Sign up to request clarification or add additional context in comments.

Comments

2
(?:^|(?<=\s))&&(?=\s|$)

Use lookarounds.Do not consume space just assert.See demo.

https://regex101.com/r/sS2dM8/39

re.sub('(?:^|(?<=\s))&&(?=\s|$)', 'and', 'x&& && &&')

Output:'x&& and and'

2 Comments

the output of this code is 'x&& and and ', not 'x&& and and'
@pabtorre there was a typo.check now
0

This seems like a very old post. Anyone looking for alternative can use the following regex as well.

re.sub(r"(\s)(\&\&)(?=(\s))", r"\1and", a)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.