Skip to main content
 首页 » 编程设计

python之如何在 Python 中从正则表达式中匹配和提取组

2025年05月04日47duanxz

我有一个程序可以接收用户的输入。

我希望能够检测到用户何时说出如下内容:

“将 HP 25 设置为 9999”

然后使用正则表达式提取 25 和 9999。

是吗:

if re.match(r"^Set HP ([\d]+) to ([\d]+)$", userstring) 

如果是这样,我如何使用正则表达式提取用户输入的两个数字?

请您参考如下方法:

使用matchobj.groups

m = re.match(r"^Set HP (\d+) to (\d+)$", userstring) 
if m: 
    print m.groups() 

例子:

>>> m = re.match(r"^Set HP (\d+) to (\d+)$", "Set HP 25 to 9999") 
>>> if m: 
    print m.groups() 
 
 
('25', '9999') 
>>>