regex - Named non-capturing group in python? -
is possible have named non-capturing group in python? example want match string in pattern (including quotes):
"a=b" 'bird=angel'
i can following:
s = '"bird=angel"' myre = re.compile(r'(?p<quote>[\'"])(\w+)=(\w+)(?p=quote)') m = myre.search(s) m.groups() # ('"', 'bird', 'angel')
the result captures quote group, not desirable here.
you need capturing group in order match same quote: there no other mechanism in re
allows this, short of explicitly distinguishing 2 quotes:
myre = re.compile('"{0}"' "|'{0}'" .format('(\w+)=(\w+)'))
(which has downside of giving four groups, 2 each style of quotes).
note 1 not need give name quotes, though:
myre = re.compile(r'([\'"])(\w+)=(\w+)\1')
works well.
in conclusion, better off using groups()[1:]
in order need, if @ possible.
Comments
Post a Comment