Reputation: 3474
I am trying to match following strings
foo=boo-40
foo=1*boo+0
foos=1/10*boo+0
foos=1*boo-32000
foos=boo*1
foos=boo*1/10
usingregex.
For doing that, I am using following regex:
'[(foo|foos)]=(?P<Pnum1>\d+)?(/?P<Pdenom1>\d+)?\*?\(?boo\)?\*?(?P<Pnum2>\d+)?(/?P<Pdenom2>\d+)?(?P<Poffset>[+-]\d+)?'
My problem is assuming Pnum1 was not found, rather then Pnum2 was found.
how do i detect which Pnum1 or Pnum2 was found?
I tried the following:
try:
if match.group('Pnum1'):
Pnum = match.group('Pnum1')
elif match.group('Pnum2'):
Pnum = match.group('Pnum2')
else:
Pnum = None
except IndexError:
Pnum = None
But this test is wrong, since in case 'Pnum1' does not exist, the code does not test for 'Pnum2' (It can be that none of them exists).
Is it possible to retrieve the found match elements? or to return a default value from match.group('Pnum2')
(like get in dictionary)?
Upvotes: 0
Views: 140
Reputation: 6847
Assuming the regexp is correct, it's better if, instead of a test, you simply do:
Pnum = match.group('Pnum1') or match.group('Pnum2')
As or
returns the first truthy value or the last falsy, if 'Pnum1'
is not None
, the variable will get the value from 'Pnum1'
. If its None
, then the value from 'Pnum2'
. If both are None
, it will become None
.
Notice this gives preference to the term you put first in the or
expression.
Upvotes: 1