Link to home
Start Free TrialLog in
Avatar of Dennie
Dennie

asked on

python findall position of matches

Hi,

I'm using re.findall to search for patterns in an entire file. Is there a way I can determine the position of the matches in the file?

Avatar of gelonida
gelonida
Flag of France image

Did you look at
http://docs.python.org/library/re.html#match-objects

Each match object supports the methods start() and stop()
My mistake:

findall() does not return match objects, but just strings.
so my above solution is not working.

You had to make your own findall(), that returns match objects

def myfindall(regex, searchstring):
    pos=0
    while True:
        match = regex.search(searchstring, pos)
        if not match:
             return
        yield match
        pos = match.end() 

myre = re.compile(r'\d+')

mystring = 'ads 123 asdas 123 dsada 22'

for match in myfindall(myre, mystring):
    print 'found at %2d: <%s>' % (match.start(), match.group())

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of gelonida
gelonida
Flag of France image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Dennie
Dennie

ASKER

many thanks!