Anonymous
Anonymous

Reputation: 3414

How can I get the offset where a Python regular expression search found a match?

I'm trying to get the offset of the match found using re.search().

http://docs.python.org/dev/howto/regex.html

This site explains how to get offsets of match components relative to the start of the match, but doesn't say how to get the offset of the match itself in the "haystack" string.

Upvotes: 6

Views: 8673

Answers (2)

BrtH
BrtH

Reputation: 2664

>>> import re
>>> s = 'Hello, this is a string'
>>> m = re.search(',\s[a-z]',s)
>>> m.group()
', t'
>>> m.start()
5

More info can be found here.

Upvotes: 8

karthikr
karthikr

Reputation: 99630

You need to do something like this:

import re

for m in re.compile("[a-z]").finditer('what1is2'):
    print m.start(), m.group()

Upvotes: 2

Related Questions