Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace multiple overlapping patterns with regex?

Tags:

python

regex

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?

like image 984
satoru Avatar asked Sep 12 '25 06:09

satoru


2 Answers

You could use non-word boundaries here.

>>> re.sub(r'\B&&\B', 'and', 'x&& && &&')
'x&& and and'
like image 102
hwnd Avatar answered Sep 14 '25 21:09

hwnd


(?:^|(?<=\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'

like image 34
vks Avatar answered Sep 14 '25 19:09

vks