Help: Arbitrary number of groups in regex

Bengt Richter bokr at oz.net
Fri Aug 9 23:49:54 CEST 2002


On Fri, 9 Aug 2002 08:16:18 +0000 (UTC), Duncan Booth <duncan at NOSPAMrcp.co.uk> wrote:

>"Jean-Philippe Côté" <cotej at crt.umontreal.ca> wrote in 
>news:AqC49.430$WJ.135248 at news20.bellglobal.com:
>
>> I'm starting to think it's impossible too. Perhaps I oversimplified
>> the problem in my. What I have is actually an arbitrary number
>> or comma separated values, each of which can be
>> composed of letters or numbers. I don't know the number in
>> advance. For instance, I might have the following input:
>> 
>> " FL234,  MK434,  9743"
>> 
>> I've tried to write a regex pattern which could return me each value
>> in a separate group, but I believe I have to 'split' the string first
>> and then parse each value separately.
>> 
>
>Why on earth do you want to use a regular expression here at all? Isn't 
>splitting on comma then stripping leading/trailing spaces sufficient:
>
>>>> aString = " FL234,  MK434,  9743"
>>>> groups = [s.strip() for s in aString.split(',')]
>>>> print groups
>['FL234', 'MK434', '9743']
>
Or
 >>> aString = " FL234,  MK434,  9743"
 >>> map(str.strip, aString.split(','))
 ['FL234', 'MK434', '9743']

But why the big reaction against regex? Not as efficient? If so, why not ?
(assuming it's compiled outside of a loop, so the setup overhead is divided
by the loop count to get the comparable single-operation cost).

Regards,
Bengt Richter



More information about the Python-list mailing list