How to get positions of multiple RE matches?

Fredrik Lundh fredrik at pythonware.com
Fri Apr 6 09:49:25 EDT 2001


Karl Schmid wrote:
> 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

better make that loop:

while 1:
    m = p.search(a, pos)
    if not m:
        break
    pos = m.start()
    print pos
    pos += 1

Cheers /F





More information about the Python-list mailing list