1

I looked through a bunch of methods the re module provides, but I couldn't seem to find one that gives the position of a pattern.

For example, consider the following code:

import re

text = '23132102301211213302'

x=re.findall(r'21',text)

print x

Output:

['21', '21', '21']

I just get a list of 21's as my output, which isn't useful for my purposes. I was wondering if there was a method similar to findall, which gives the positions of 21's, and not just 21's (i.e the first 21 occurs in position 4, the second in position 11...)

2313*21*02301211213302 --> position: 4

23132102301*21*1213302 --> position: 11

23132102301211*21*3302 --> position: 14

So the desired output should be [4,11,14]. Is there a re method for this?

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
Shuvro
  • 11
  • 1
  • http://stackoverflow.com/questions/3519565/find-the-indexes-of-all-regex-matches-in-python – dting Mar 13 '11 at 05:06

1 Answers1

2

re.finditer() gives you MatchObjects which among other things make the position available.

The beginning of the match object m is given by m.start(), and the end by m.end() if you want that too.

Amber
  • 507,862
  • 82
  • 626
  • 550