Help with regular expression

S

Stephen Boulet

I'm trying to write an RE to match a string that might or might not be
ther and everything past it up to another string that might or might not
be there and everything past it to a third string that might or might
not be there and everything past it.

Say my strings are "STRING1", "STRING2", and "String3".

Would the re be:

r'((STRING1.*)(STRING2.*)(STRING3.*))'

The goal is to separate the groups by newlines, but I only want the
first group to match up to the second group and the second to match up
to the third.

Normally I would achieve this by typing:

pat = re.compile(r'((STRING1.*)(STRING2.*)(STRING3.*))')
m = pat.findall(s)
s = '\n\n'.join(m[0])

but the first group would seem to match everything.

How can I get it to do what I want?

-- Stephen
 
A

anton muhin

Stephen said:
I'm trying to write an RE to match a string that might or might not be
ther and everything past it up to another string that might or might not
be there and everything past it to a third string that might or might
not be there and everything past it.

Say my strings are "STRING1", "STRING2", and "String3".

Would the re be:

r'((STRING1.*)(STRING2.*)(STRING3.*))'

The goal is to separate the groups by newlines, but I only want the
first group to match up to the second group and the second to match up
to the third.

Normally I would achieve this by typing:

pat = re.compile(r'((STRING1.*)(STRING2.*)(STRING3.*))')
m = pat.findall(s)
s = '\n\n'.join(m[0])

but the first group would seem to match everything.

How can I get it to do what I want?

-- Stephen

Try non-greedy wildcards: r'((STRING1.*?)(STRING2.*?)(STRING3.*?))'
- - -

should do the trick.

hth,
anton.
 
U

Ulrich Petri

anton muhin said:
Try non-greedy wildcards: r'((STRING1.*?)(STRING2.*?)(STRING3.*?))'
- - -

Since you said that each of the three strings might or not be there you
would need:

r'((STRING1.*?)?(STRING2.*?)?(STRING3.*?)?)'

Ciao Ulrich
 

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

No members online now.

Forum statistics

Threads
474,164
Messages
2,570,898
Members
47,439
Latest member
shasuze

Latest Threads

Top