Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using regular expression to split string in python

Tags:

python

regex

I use

re.compile(r"(.+?)\1+").findall('44442(2)2(2)44')

can get

['4','2(2)','4']

, but how can I get

['4444','2(2)2(2)','44']

by using regular expression?

Thanks

like image 749
Peter Chen Avatar asked Jul 11 '26 22:07

Peter Chen


1 Answers

No change to your pattern needed. Just need to use to right function for the job. re.findall will return a list of groups if there are capturing groups in the pattern. To get the entire match, use re.finditer instead, so that you can extract the full match from each actual match object.

pattern = re.compile(r"(.+?)\1+")
[match.group(0) for match in pattern.finditer('44442(2)2(2)44')]

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!