0

I am having issues with matching this particular regex in python, can someone see what is wrong?

Sample strings I am trying to match with a single regular expression are:

string = '[Pre-Avatar Mode Cost: 5.50 MP]'
string = '[Pre-Avatar Mode Cost: 1.2 MP]'
string = '[Pre-Avatar Mode Cost: 0.5 MP]'
string = '[Post-Avatar Mode: 0 MP]'

I have tried the following, but there doesnt seem to be a single expression that matches all of them:

m = re.match('\[.*(?P<cost>\d+(\.\d+)).*\]', string) # Appears to match only ones with #.#
m = re.match('\[.*(?P<cost>\d+(\.\d+)?).*\]', string) # Appears to match the 0 only, unable to print out m.groups for the others

I am trying to catch (5.50, 1.2, 0.5, 0, etc.)

6
  • which part of the string you're trying to match? Commented Oct 29, 2012 at 17:19
  • 1
    You should provide a reproducible example, like string = "[Pre-Avatar Mode Cost: 5.50 MP]", and m = re.match('[.*(?P<cost>\d+(\.\d+)).*\]', string) Commented Oct 29, 2012 at 17:19
  • Seems like you're missing the : and whitespaces. Commented Oct 29, 2012 at 17:19
  • I am trying to catch the Numerical Part. Commented Oct 29, 2012 at 17:19
  • 2
    Did you ever get around to trying my answer to your previous question on this? Commented Oct 29, 2012 at 17:28

2 Answers 2

2

You need to make the first .* match non-greedy (add a ?), it'll swallow the numbers otherwise:

r'\[.*?(?P<cost>\d+(?:\.\d+)?).*\]'

I've also made the optional .number part a non-capturing group to simplify processing the output:

>>> import re
>>> costre = re.compile(r'\[.*?(?P<cost>\d+(?:\.\d+)?).*\]')
>>> costre.match('[Post-Avatar Mode: 0 MP]').groups()
('0',)
>>> costre.match('[Post-Avatar Mode: 5.50 MP]').groups()
('5.50',)
>>> costre.match('[Post-Avatar Mode: 1.2 MP]').groups()
('1.2',)
Sign up to request clarification or add additional context in comments.

Comments

1

I'd suggest using the : as the anchor. That way, you get a more robust expression:

r'\[.*: (?P<cost>\d+(?:\.\d+)?).*\]'

You might even want to add on the MP suffix if it's guaranteed to be in the text.

Comments

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.