繁体   English   中英

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

[英]How do match and extract groups from regex in Python?

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

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

“将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')
>>> 

您可以使用re.findall

>>> s = "Set HP 25 to 9999"
>>> re.findall('\d+', s)
['25', '9999']

或手动提取组:

>>> match = re.match(r"^Set HP (\d+) to (\d+)$", s)
>>> match.group(1)
'25'
>>> match.group(2)
'9999'

请注意, match.groups()将为您提供所有组作为一个元组:

>>> match.groups()
('25', '9999')

您还可以迭代找到数字,例如:

for m in re.finditer(r"\d+",userstring):
   print m.group()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM