Finding the carret position in a regular expression

T

Tool69

Hi,
supposed I've got the following text :

mytext = "for <myvar> in <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 :
<myvar> was found at position 5 in mytext
<somelist> was 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
 
F

Fredrik Lundh

Tool69 said:
supposed I've got the following text :

mytext = "for <myvar> in <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 :
<myvar> was found at position 5 in mytext
<somelist> was 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>
 

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,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top