Q: How to get positions of multiple RE matches?

Karl Schmid schmid at ice.mpg.de
Fri Apr 6 08:47:49 EDT 2001


I would like to get the all positions of a pattern match in a string.

Is there a more elegant solution to this problem than the following one?

>>> import re
>>> a = 'This module provides regular expression matching operations 
similar to those found in Perl'
>>> import re
>>> p = re.compile('(o)')
>>> pos = 0
>>> while p.search(a, pos):
...    pos = p.search(a, pos).start()
...    print pos
...    pos += 1

output:
6
14
37
49
56
69
73
78

Karl

-- 
----------------------------------------------------------------------
Karl Schmid                                  
Max-Planck-Institute for Chemical Ecology  
Carl-Zeiss-Promenade 10                         Tel: +49 3641 / 643658   
07745 Jena                                      Fax: +49 3641 / 643669
Germany                                       Email: schmid at ice.mpg.de
======================================================================



More information about the Python-list mailing list