[Tutor] regex grouping/capturing
Andreas Perstinger
andipersti at gmail.com
Thu Jun 13 20:09:02 CEST 2013
On 13.06.2013 17:09, Albert-Jan Roskam wrote:
> I have a string of the form "required optional3 optional2 optional1
> optional3" ('optional' may be any kind of string, so it's not simply
> 'optional\d+'.
> I would like to use a regex so I can distinguish groups. Desired
> outcome: ('required', 'optional3', 'optional2', 'optional1',
> 'optional3'). Below is a fragment of the many things I have tried.
[SNIP]
> How can I make this work?
If you really want to use a regex:
>>> import re
>>> s = "required optional3 optional2 optional1 optional3"
>>> s2 = "required optional1 optional2 optional3"
>>> pattern = "required|optional1|optional2|optional3"
>>> re.findall(pattern, s)
['required', 'optional3', 'optional2', 'optional1', 'optional3']
>>> re.findall(pattern, s2)
['required', 'optional1', 'optional2', 'optional3']
But why not simply:
>>> s.split()
['required', 'optional3', 'optional2', 'optional1', 'optional3']
>>> s2.split()
['required', 'optional1', 'optional2', 'optional3']
Bye, Andreas
More information about the Tutor
mailing list