Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple group matches for single regex

Tags:

python

regex

I'm parsing a log with python and need quick fetch some values from it

this is the simple equivalent regex and usage example

pat = re.compile("(1(2[3456]+2)+1)*")

It doesn't work as expected, only the last match group is returned by pat.match().groups()

What is the simplest solution for such problems?

updated (as wiki engine says to use edit rather than creating new post):

I need repeated matches, of course.

to_match="1232112542254211232112322421"

regex find need to be applyed twice recursively. I can bear it, but is there any options?

like image 959
ayvango Avatar asked Nov 04 '22 11:11

ayvango


1 Answers

Ok, try this (but only after you learned how to accept answers ;-) )

s = "123321124421125521"
pat = re.compile("(1(2[3456]+2)+1)")
print pat.findall(s)

remove the quantifier and use instead findall(). This will result in this list:

[('123321', '2332'), ('124421', '2442'), ('125521', '2552')]

like image 69
stema Avatar answered Nov 09 '22 13:11

stema