简体   繁体   中英

multiple group matches for single 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?

You are repeating a captured group instead of capturing a repeated group and that is the reason why you are getting only the last capture.

You should be using

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

See here for more on repeating a captured group vs capturing a repeated group http://www.regular-expressions.info/captureall.html

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')]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM