我想知道如何通过索引导航 finditer 正则表达式操作生成的对象。
我的字符串是s =“鱼油X22叠花生C4”
这是我的代码:
import re
words = re.finditer('\S+', s)
has_digits = re.compile(r'\d').search
for word in words:
if has_digits(word.group()):
print (the word that is two words back)
期望的输出=
fish
stack
最佳答案
您可以使用deque
来保存元素。那么这就变得容易了:
import re
from collections import deque
s = 'fish oil X22 stack peanut C4'
words = re.finditer('\S+', s)
has_digits = re.compile(r'\d').search
deq = deque([],2)
for word in words:
wordtxt = word.group()
if has_digits(wordtxt):
print (deq[0])
deq.append(wordtxt)
有点不清楚字符串会发生什么:
s = 'fish oil X22 stack C4'
应该打印“fish”和“oil”还是“fish”和“X22”。另外,如果第一个子字符串是“X22”怎么办?在我的回答中,这将导致 IndexError
,但很难知道你想用它做什么......
关于python - 使用 re.finditer 按索引循环匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16109990/