Regex findall matches letters "a" to "z" in a string followed by another character

Viewed 218

Result should return list which contains letter a to c followed by another character

Text is aabbcc I would expect it return ['a', 'a', 'b', 'b', 'c']

import re
text = 'aabbcc'
result = re.findall(r'([a-c]).', text)
print(result)

but it returns ['a', 'b', 'c']

2 Answers

Use a non-capturing lookahead ([a-z](?=.)). This is basically the same as what you had, but doesn't capture the next character.

To make it work the way you have it, simply import regex instead of re module and use the overlapped parameter:

import regex
text = 'aabbcc'
result = regex.findall(r'([a-c]).', text, overlapped = True)
print(result)

Prints:

['a', 'a', 'b', 'b', 'c']

Otherwise a positive lookahead mentioned in comments and other answers is an option.

Related