Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get overlapping string in regular expression python [duplicate]

Tags:

python

regex

I have tried

re.findall(r'(\d\*\*\d)','3*2**3**2*5**4**')

The output is ['2**3', '5**4']. My desired output is ['2**3','3**2', '5**4']. What change is needed in re?

like image 327
sandepp Avatar asked Sep 28 '26 19:09

sandepp


1 Answers

Change your regex to use a lookahead assertion which will not consume the string while matching:

import re

string = '3*2**3**2*5**4**'
print(re.findall(r'(?=(\d\*\*\d))', string))
>> ['2**3', '3**2', '5**4']
like image 110
DeepSpace Avatar answered Oct 01 '26 17:10

DeepSpace