470,636 Members | 1,601 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,636 developers. It's quick & easy.

re.findall

A question about the findall function in the re module, and I also
would be happy with pointers to online documentation with which I
could have found a solution myself (if it even exists!).

I have this program and result:

-------------- program ------------------
import re

pat = r'(.*) or (.*)'
r = re.findall(pat, "i or j or k")
print r
-------------- result -------------------
[('i or j', 'k')]
-------------------------------------------

But the result I want is this:
[('i', 'j or k'), ('i or j', 'k')]

So my regular expression is wrong, but also variations like
r'^(.*|.*?) or (.*|.*?)$' do not work. I have the feeling I am
overlooking something simple. Maybe I should not try to use
re.findall to get the desired result, but do a re.match in a
while-loop?

Stated in English the problem is this: give me all combinations of
strings left and right of r' or ', and return them as a list of
tuples. Sure I can solve this without using the re module, using
while-loops and string.search etc., but I also have variations of
this problem and learning re seems useful.
Jul 18 '05 #1
1 3177
hw***@hotmail.com (Will Stuyvesant) wrote in
news:cb**************************@posting.google.c om:
A question about the findall function in the re module, and I also
would be happy with pointers to online documentation with which I
could have found a solution myself (if it even exists!).


The problem is that the strings you want to find are overlapping.
This should get you started:

import re

s = "i or j or k or grr"
pat = re.compile(r'\w+ or \w+')

startposition = 0
while 1:
res = pat.search(s, startposition)
if res == None:
break
startposition = res.start() + 1
print res.group()
Matthias
Jul 18 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

3 posts views Thread by Michael Rockwell | last post: by
1 post views Thread by JerryB | last post: by
3 posts views Thread by DagoFlores | last post: by
5 posts views Thread by David Longnecker | last post: by
7 posts views Thread by Abhishek | last post: by
2 posts views Thread by =?Utf-8?B?bWdvbnphbGVzMw==?= | last post: by
1 post views Thread by Doug | last post: by
2 posts views Thread by Alexnb | last post: by
1 post views Thread by Korara | last post: by
???
reply views Thread by Stoney L | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.