I want to write a program which finds palindromes (words which are the same from start to end and end to start like anna
).
But it should also work for multiple words car a rac
and inside sentences asdcar a racbnm
.
I wrote a regular expression to find the span of a start of a palindrome:
([a-z])(\s*)[a-z]?(\\2)(\\1)
It finds a letter then there can be spaces, then there can be another letter, spaces again, and the first letter again.
It works fine but for the string xxxxx
it behaves strange:
import re
p = re.compile('([a-z])(\s*)[a-z]?(\\2)(\\1)')
finds = p.finditer('xxxxx')
for m in finds:
print m.span()
output
(0, 3)
(3, 5)
It doesn't find the one I'm searching for: (1, 4)
What´s wrong with my re?
Edit: it should just find the start of the palindrome. The algorithm will do the rest.