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

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


Franz Steinhaeusler wrote:
> given a string:
> 
> st="abcdatraataza"
>     ^   ^     ^ ^ (these should be found)
> I want to get the positions of all single 'a' characters.
> (Without another 'a' neighbour)
> 
> So I tried: 
> r=re.compile('[^a]a([^a]') 
> 
> but this applies only for 
> the a's, which has neighbours.
> So I need also '^a' and 'a$'.
> 
> Am I doing something wrong? 
> Is there a easier solution?
> How can I quickly get all these positions?
> 
> Thank you in advance.

import re
s='abcdatraataza'
r=re.compile('(?<!a)a(?!a)')
a_list=[ match.start() for match in re2.finditer(s) ]

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



More information about the Python-list mailing list