# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"""
(?(DEFINE)
(?<palindrome>
# Recursive alternative first to match recursive palindromes.
# Invert alternatives order to match nested palindromes individually
# and (drastically) reduce backtracking.
(?<l1>\p{L})\p{M}* [\s\p{P}]* (?&palindrome) [\s\p{P}]* \k<l1>\p{M}*
| (?<l2>\p{L})\p{M}* [\s\p{P}]* \k<l2>\p{M}*
| \p{L}\p{M}*
)
)
(?<=[\s\p{P}]|^) (?&palindrome) (?(?=\s*\p{P}) (?:\s*\p{P})+ | (?=\s|$))
"""
test_str = ("~ should not match\n"
"jambon\n\n"
"~ Simple\n"
"a\n"
"bb\n"
"cc\n"
"ddd\n"
"bob\n"
"ara\n"
"abbb a\n"
"radar\n"
"essayasse\n\n"
"~ Spaces, diacritics and punctuation\n"
"Don't nod!Step on no pets.\n"
"Ésope reste ici et se repose.\n"
"Élu par cette crapule ! ?\n"
"Tu l'as trop écrasé, César, ce Port-Salut !\n"
"Zeus a été à Suez.\n\n"
"~ Recursive palindromes\n"
"a a !\n"
"ah ha !\n"
"abba / ab b a\n"
"~\n"
"abba été àb ba\n"
"~\n"
"abba, ab b a, abbà été àb ba")
subst = "[$0]"
# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.IGNORECASE | re.VERBOSE)
if result:
print (result)
# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Python, please visit: https://docs.python.org/3/library/re.html