[英]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.