Skip to main content
 首页 » 编程设计

python之python 中的正则表达式之找不到特定的字符串

2025年05月04日16xiaohuochai

我开始在 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) 
                    ^^ 

它匹配一个数字,但是 \merchant 中的 \m 仍然是 m。但是,您应该删除 \ID 和 \device 之前的 \,例如:

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