python - 使用 re.finditer 按索引循环匹配

标签 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)

期望的输出=

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/

相关文章:

regex - VBA - 带有变量的正则表达式拆分

javascript - 这个正则表达式的解释

c# - 如何在这样一个简单的字符串中分别获取整数和字符?

python - 如何从 .xlsx 文件的内容获取字典?

python - Python UnitTest 中的 assertEqual 应该做什么?

python - Sympy 找不到 sinh (t) 的拉普拉斯变换

regex - 在 Vim 中匹配单引号或双引号字符串

python - 从文件中删除在 Python 中没有特定单词的行

python - 在数据框中除一列(不删除它)之外的所有列上填充 NaN 值

ruby-on-rails - 简单 - 使用 String#scan 提取电子邮件地址