I am using python's re module and I would like to search and capture one of two possible items, but I can't figure out how to get the grouping and non capturing grouping to work right:
Lets say my pattern is:
(?:(test)55)|(apple)
So basically I want to capture 'test' or 'apple' but only capture 'test' if it is followed by 55.
The problem here is that I end up with 2 capture groups so I end up with either (None, 'apple') or ('test', None).
I know that I can just post-process it:
next( item for item in groups() if item is not None)
but I was wondering if there is a way to phrase it in the regex that would make it work (I just want to learn regex better).
Thanks.
(test)is a capturing group, too.lastindexattribute that returns the index of the last capturing group that matched something. If the capture groups are mutually exclusive, like in your example, your post processing could be simplified tomatchobject.group(matchobject.lastindex)