2016-07-07 19 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