import Foundation
let pattern = ##"""
(?(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|$))
"""##
let regex = try! NSRegularExpression(pattern: pattern, options: [.caseInsensitive, .allowCommentsAndWhitespace])
let testString = #"""
~ 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
"""#
let stringRange = NSRange(location: 0, length: testString.utf16.count)
let substitutionString = #"[$0]"#
let result = regex.stringByReplacingMatches(in: testString, range: stringRange, withTemplate: substitutionString)
print(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 Swift 5.2, please visit: https://developer.apple.com/documentation/foundation/nsregularexpression