2016-07-07 59 views
-3

在python脚本中,我使用re.finditer来查找文本文件中的字符串。找不到re.finditer搜索字符串 - 如何实现

如何知道re.finditer是否找不到特定的字符串?

我试着用

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

但是,这是行不通的。

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

最新蟒蛇

+0

校正....... – eckhart

+0

'如果不是re.search(“串“,line2):print(”empty“)' – YOU

+1

请将*”不起作用“*替换为问题的实际解释,以及包含输入的[mcve]。 – jonrsharpe

回答

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") 
+0

由于某种原因,这没有奏效。我在第2行中改变了一些行,但找不到“空”,但不会抛出... – eckhart

+0

对不起,当然它不起作用,因为我正在循环一个空的迭代器。我更新了可以工作的代码。 –

+0

请注意,这是你原来的代码不起作用的原因:在re.finditer(“字符串”,第2行)中的n:'循环根本不运行,因为' re.finditer结果。 –

0

如果正则表达式模式在您正在搜索的文本的任何地方都不匹配,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