Python 使用re.finditer按索引循环匹配
我想知道如何通过索引导航finditer正则表达式操作生成的对象 我的字符串是Python 使用re.finditer按索引循环匹配,python,regex,Python,Regex,我想知道如何通过索引导航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) 期望输出= fi
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'
它应该打印“鱼”和“油”还是“鱼”和“X22”。另外,如果第一个子字符串是“X22”,该怎么办?在我的回答中,这将导致一个索引器,但很难知道您想用它做什么…您可以使用,并且:
如何检查第一个子字符串是否为X22以避免错误?您可以将其包装为try/except。你想发生什么?如果第二个元素是X22呢?有很多选择,但最佳选择实际上取决于您在这些情况下想要的行为。我将测试您的解决方案
import re
import itertools as it
s = "fish oil X22 stack peanut C4"
words = re.finditer('\S+', s)
has_digits = re.compile(r'\d').search
words, words_copy = it.tee(words)
next(words); next(words) #Skip the first two words of one iterator
for word, back_word in it.izip(words, words_copy):
if has_digits(word.group()):
print(back_word.group())