How to access multiple group matches?

  • Thread starter Christoph Krammer
  • Start date
C

Christoph Krammer

Hello,

I want to use the re module to split a data stream that consists of
several blocks of data. I use the following code:

iter = re.finditer('^(HEADER\n.*)+$', data)

The data variable contains binary data that has the word HEADER in it
in some places and binary data after this word till the next
appearance of header or the end of the file. But if I iterate over
iter, I only get one match and this match only contains one group. How
to access the other matches? Data may contain tens of them.

Thanks in advance,
Christoph
 
G

Gary Herron

Christoph said:
Hello,

I want to use the re module to split a data stream that consists of
several blocks of data. I use the following code:

iter = re.finditer('^(HEADER\n.*)+$', data)

The data variable contains binary data that has the word HEADER in it
in some places and binary data after this word till the next
appearance of header or the end of the file. But if I iterate over
iter, I only get one match and this match only contains one group. How
to access the other matches? Data may contain tens of them.

Thanks in advance,
Christoph

Use .*? instead of .* in your regular expression.


From the manual page:

*|*?|, |+?|, |??|*
The "*", "+", and "?" qualifiers are all /greedy/; they match as
much text as possible. Sometimes this behaviour isn't desired; if
the RE <.*> is matched against |'<H1>title</H1>'|, it will match the
entire string, and not just |'<H1>'|. Adding "?" after the qualifier
makes it perform the match in /non-greedy/ or /minimal/ fashion; as
/few/ characters as possible will be matched. Using .*? in the
previous expression will match only |'<H1>'|.

Gary Herron
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,053
Latest member
BrodieSola

Latest Threads

Top