By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,345 Members | 1,790 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,345 IT Pros & Developers. It's quick & easy.

Finding the carret position in a regular expression

P: n/a
Hi,
supposed I've got the following text :

mytext = "for <myvarin <somelist>:"

with the following simple pattern : pattern = "<[a-z]+>"

I use re.findall(pattern, mytext) wich returns :
['<myvar>','<somelist>']

Now, I want my prog to return the positions of the returned list
elements, ie :
<myvarwas found at position 5 in mytext
<somelistwas found at position 16 in mytext

How can I implement this ? Sorry if it's trivial, that's the first time
I use regular expressions.
Thanks,
6Tool9

Nov 23 '06 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Tool69 wrote:
supposed I've got the following text :

mytext = "for <myvarin <somelist>:"

with the following simple pattern : pattern = "<[a-z]+>"

I use re.findall(pattern, mytext) wich returns :
['<myvar>','<somelist>']

Now, I want my prog to return the positions of the returned list
elements, ie :
<myvarwas found at position 5 in mytext
<somelistwas found at position 16 in mytext
"findall" doesn't return that information; use "finditer" instead, and
use the "span" or "start" method on the returned match object to get the
position:

for m in re.finditer(pattern, mytext):
print m.span()

</F>

Nov 23 '06 #2

P: n/a
Thanks Fredrik,
I was not aware of finditer. Iterators are very usefull !

Nov 23 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.