Regex for repeated character?

John Machin sjmachin at lexicon.net
Thu Jun 16 09:24:41 EDT 2005


Peter Otten wrote:
> Leif K-Brooks wrote:
> 
> 
>>How do I make a regular expression which will match the same character
>>repeated one or more times, instead of matching repetitions of any
>>(possibly non-same) characters like ".+" does? In other words, I want a
>>pattern like this:
>>
>> >>> re.findall(".+", "foo") # not what I want
>> ['foo']
>> >>> re.findall("something", "foo") # what I want
>> ['f', 'oo']
> 
> 
> This is as close as I can get:
> 
> 
>>>>[m.group() for m in re.compile(r"(.)(\1*)").finditer("foo bar baaaz")]
> 
> ['f', 'oo', ' ', 'b', 'a', 'r', ' ', 'b', 'aaa', 'z']
> 

Another way, ever so slightly less complicated:

 >>> [x[0] for x in re.findall(r"((.)\2*)", "foo bar baaaz")]
['f', 'oo', ' ', 'b', 'a', 'r', ' ', 'b', 'aaa', 'z']

Cheers,
John



More information about the Python-list mailing list