找到常量后查找下一个模式

时间:2013-06-27 14:00:27

标签: python regex python-2.7

我有一个单词列表,想知道下一个单词的位置或索引,它遵循某种模式(这是一个简单的例子,但正则表达式是一种必要的恶魔)

list = ["A","B","C","D","A","B","C","D","A","B","-","C","D"]

现在我找到了" A"

的位置
a = [i for i,x in enumerate(list) if x == "A"]

但是,如果我想找到" C"每次" A"找到,然后以下一个" A"再次递归开始。

1 个答案:

答案 0 :(得分:1)

list.index有一个可选参数start,您可以使用它来指定起始索引。

>>> lis = ["A","B","C","D","A","B","C","D","A","B","-","C","D"]
>>> for i,x in enumerate(lis):
...     if x == 'A':
...         print "next 'C' found at",lis.index('C',i)
...         
next 'C' found at 2
next 'C' found at 6
next 'C' found at 11

<强>更新

>>> import re
>>> strs =  "".join(lis)
>>> strs
'ABCDABCDAB-CD'
>>> r = re.compile(r'A[^C]+C')
>>> [m.end()-1 for m in r.finditer(strs)]
[2, 6, 11]
#or
>>> r = re.compile(r'A[^C]+')
>>> [m.end() for m in r.finditer(strs)]
[2, 6, 11]