找不到re.finditer搜索字符串 - 如何实现

时间:2016-07-07 07:02:25

标签: python text

在python脚本中,我使用re.finditer在文本文件中查找字符串。

我怎么知道re.finditer是否找不到特定的字符串?

我试过

for n in re.finditer("string",line2):
    if n.start() == "":
        print("empty")

但这不起作用。

(我想使用re.finditer,因为它已经在脚本中)

最新的蟒蛇

2 个答案:

答案 0 :(得分:3)

如果正在搜索的文本中的正则表达式模式不匹配,finditer将返回空的可迭代。也就是说,您的for循环将永远不会在缩进块中运行代码。

有几种方法可以检测到这一点。一种可能是设置n循环变量的初始值,然后测试它是否已被循环代码更新:

n = None

for n in re.finditer(pattern, text):
    ... # do stuff with found matches here

if n is None:    # n was never assigned to by the loop code
    ... # do stuff for no match situation here

答案 1 :(得分:0)

根据这些要求,您可以执行以下操作:

n = re.finditer(pattern, line2)
try:
    first_item = next(n)
    #do something with the rest of the iterable eg:
    print(first_item)
    for item in n:
        print(n)
except StopIteration:
    print("empty")