Reputation: 403
I want to do capture two groups, but one is inside a non-capture group. i.e.
import re
text = 'column{fields}'
parsed = re.search(r'(\w+)(?:{(\w+)})', text)
parsed.groups() # prints ('column', 'fields')
That works, however if my text is only 'column'
, regex
is NoneType.
Upvotes: 5
Views: 1604
Reputation: 785126
You can make 2nd non-capturing group optional:
>>> text = 'column'
>>> parsed = re.search(r'(\w+)(?:{(\w+)})?', text)
>>> parsed.groups()
('column', None)
?
at the end of (?:{(\w+)})?
will make part after column
i.e. (?:{(\w+)})
optional.
Upvotes: 2