2015-12-21 124 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。

相关问题