开发者

Finding the position of a pattern using the re module in Python

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜