简体   繁体   中英

How do match and extract groups from regex in Python?

I have a program where I am taking in input from a user.

I want to be able to detect when the user says something like:

"Set HP 25 to 9999"

and then extract both the 25 and 9999 using regex.

Is it:

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

and if so, how do I extract the two numbers the user entered also using regex?

use matchobj.groups

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

Example:

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


('25', '9999')
>>> 

You can either use re.findall

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

or extract the groups manually:

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

note that match.groups() will give you all groups as a tuple:

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

You can also find the numbers iteratively like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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