Finding the carret position in a regular expression

Fredrik Lundh fredrik at pythonware.com
Thu Nov 23 04:56:32 EST 2006


Tool69 wrote:

> 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>




More information about the Python-list mailing list