+ 2

i wrote a code to search for palindromes

import re word = "hannah" pattern = "(\w+)\1" if re.search(pattern, word): print(word) then i realised that the pattern i wrote can identify "hanhan" not hannah....somebody plz tell me how can i search for reversed group using regular expressions

21st May 2020, 4:38 PM
PRO
PRO - avatar
2 ответов
+ 3
I'm pretty sure there is no actual way of doing that with pure regex, at least not for strings of arbitrary length (there might be ways of finding palindromes of given length, though). There are, of course, much more efficient ways of doing this, with just simple string slicing techniques, like: https://code.sololearn.com/cgtlGQC2E04W/?ref=app https://code.sololearn.com/cR4DVjNP4rXd/?ref=app
21st May 2020, 8:31 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
0
I know it doesn't help you with your issue in Python. But maybe it is interesting that there exists a solution for this in .NET, which might find its way into other languages... Have a look at balancing groups: https://regular-expressions.mobi/balancing.html https://code.sololearn.com/ckHsIDV5m14F/?ref=app
21st May 2020, 9:21 PM
Manu_1-9-8-5
Manu_1-9-8-5 - avatar