re = /(?(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|$))/ix
str = '~ should not match
jambon
~ Simple
a
bb
cc
ddd
bob
ara
abbb a
radar
essayasse
~ Spaces, diacritics and punctuation
Don\'t nod!Step on no pets.
Ésope reste ici et se repose.
Élu par cette crapule ! ?
Tu l\'as trop écrasé, César, ce Port-Salut !
Zeus a été à Suez.
~ Recursive palindromes
a a !
ah ha !
abba / ab b a
~
abba été àb ba
~
abba, ab b a, abbà été àb ba'
subst = '[$0]'
result = str.gsub(re, subst)
# Print the result of the substitution
puts result
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 Ruby, please visit: http://ruby-doc.org/core-2.2.0/Regexp.html