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

如何在Python中从正则表达式中匹配和提取组?,python,regex,Python,Regex,我有一个程序,我从用户那里获取输入 我希望能够检测到用户何时说: “将HP 25设置为9999” 然后使用正则表达式提取25和9999 是: if re.match(r"^Set HP ([\d]+) to ([\d]+)$", userstring) 如果是这样,我如何提取用户也使用regex输入的两个数字?使用matchobj.groups m = re.match(r"^Set HP (\d+) to (\d+)$", userstring) if m: print m.grou

我有一个程序,我从用户那里获取输入

我希望能够检测到用户何时说:

“将HP 25设置为9999”

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

是:

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

如果是这样,我如何提取用户也使用regex输入的两个数字?

使用
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')
>>> 

使用
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')

您可以使用
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()

您还可以迭代地找到这些数字,如:

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

没有必要在单个项目中使用括号。。。对于多个项目,您必须使用它们。没有必要在单个项目中使用括号。。。对于多个,您必须使用它们。
filter(str.isdigit,userstring.split())
filter(str.isdigit,userstring.split())