我开始在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.
我究竟做错了什么?
因为:
ex_2 = re.findall(r'\device\b\s\ID\b\s\d+', string_1)
^^
其中一些比赛,但\m
在\merchant
仍然是m
。但是,您应该删除\
之前\ID
和\device
类似的内容:
>>> re.findall(r'device\b\sID\b\s\d+', string_1)
['device ID 45678']
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句