2015-12-21 39 views
1

我開始學習在Python正則表達式,我已經得到了以下任務:正則表達式 - 無法找到特定字符串

我需要編寫一個腳本採取這些兩個字符串:

string_1 = 'merchant ID 1234, device ID 45678, serial# 123456789' 

string_2 = 'merchant ID 8765, user ID 531476, serial# 87654321' 

並僅顯示其中包含merchant ID ####device ID ####的字符串。

要檢查我寫了下面行的第一個條件:

ex_1 = re.findall(r'\merchant\b\s\ID\b\s\d+', string_1) 
print (ex_1) 

output: ['merchant ID 1234'] - works fine! 

問題是我不能讓其他條件因爲某些原因:

ex_2 = re.findall(r'\device\b\s\ID\b\s\d+', string_1) 

output: [] - empty list. 

我在做什麼錯?

+0

您可以使用像https://regex101.com/這樣的網絡工具。 – alpert

回答

5

因爲:

ex_2 = re.findall(r'\device\b\s\ID\b\s\d+', string_1) 
        ^^ 

其中許多比賽,但在\m仍然\merchantm。然而,你應該刪除\\ID\device像以前一樣:

>>> re.findall(r'device\b\sID\b\s\d+', string_1) 
['device ID 45678'] 
1

您的分組是錯誤的。使用括號進行分組:

(merchant ID \d+|device ID \d+) 

例如,

>>>re.findall('(merchant ID \d+|device ID \d+)', string_1) 
['merchant ID 1234', 'device ID 45678'] 
0

請注意特殊字符'\''\device\'符合[0-9] + 'evice'。 隨着Pythex你可以測試你的正則表達式,並參考一個偉大的cheatsheet。

相關問題