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.)
You need to make the first
.*match non-greedy (add a?), it’ll swallow the numbers otherwise:I’ve also made the optional
.numberpart a non-capturing group to simplify processing the output: