Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 412
Anonymous Avatar asked Apr 06 '13 22:04

Anonymous


2 Answers

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

like image 106
BrtH Avatar answered Sep 29 '22 05:09

BrtH


You need to do something like this:

import re

for m in re.compile("[a-z]").finditer('what1is2'):
    print m.start(), m.group()
like image 35
karthikr Avatar answered Sep 29 '22 04:09

karthikr