RegEx: find all occurances of a single character in a string

P at draigBrady.com P at draigBrady.com
Tue Dec 14 18:47:47 CET 2004


P at draigBrady.com wrote:
> P at draigBrady.com wrote:
> 
>> import re
>> s='abcdatraataza'
>> r=re.compile('(?<!a)a(?!a)')
>> a_list=[ match.start() for match in re2.finditer(s) ]
>>
> 
> Oops, tested this time:
> ----------------------------
> 
> import re
> 
> 
> def index_letters(s,l):
>     regexp='(?<!%s)%s(?!%s)' % (l,l,l)
>     r=re.compile(regexp)
>     return [ match.start() for match in r.finditer(s) ]
> 
> 
> print index_letters('abcdatraataza','a')

Just comparing Fredrik Lundh's method:

r=re.compile("a+")
[m.start() for m in r.finditer(s) if len(m.group()) == 1]

Mine runs 100K iterations of 'abcdatraataza','a' in 1.4s
whereas Fredrik's does the same in 1.9s

-- 
Pádraig Brady - http://www.pixelbeat.org
--



More information about the Python-list mailing list