1

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?

0

3 Answers 3

4

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')
>>> 
Sign up to request clarification or add additional context in comments.

1 Comment

it's unnecessary to use brackets interms of single item... For more than one, you must use them..
1

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

Comments

0

You can also find the numbers iteratively like:

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

1 Comment

filter(str.isdigit, userstring.split())

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.