parsing combination strings

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Wed Mar 21 17:16:47 EDT 2007


PKKR a écrit :
> On Mar 21, 2:51 pm, "Steven D. Arnold" <stev... at neosynapse.net> wrote:
> 
>>On Mar 21, 2007, at 2:42 PM, PKKR wrote:
>>
>>
>>>I need a fast and efficient way to parse a combination string(digits +
>>>chars)
>>
>>>ex: s = "12ABA" or "1ACD" or "123CSD" etc
>>
>>>I want to parse the the above string such that i can grab only the
>>>first digits and ignore the rest of the chacters,
>>
>>A regex leaps to mind.....have you investigated the "re" module?
>>
>> >>> import re
>> >>> re.match(r'(\d+)', '123abc').group(1)
>>'123'
>>
>>steven
> 
> 
> 
> yep thats what i tried as per tommy's advice and came up with:
> 
> re.split('[^0-9]', str)[0]

avoid using 'str' as an identifier (unless it's ok for you to shadow the 
builtin string type)

> or is there a better way?
> 
exp = re.compile(r'^([0-9]+)')
for s in ["12ABA", "1ACD", "123CSD"]:
     print exp.match(line).group(0)
=> 12
=> 1
=> 123



More information about the Python-list mailing list