Reputation: 1406
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.
Upvotes: 0
Views: 112
Reputation: 50220
To capture only one group, use just one group of capturing parentheses containing (test|apple)
. Add a lookahead so that test must be followed by 55
:
re.findall(r"(test(?=55)|apple)", mystring);
Upvotes: 1