How to check if a string is a palindrome ignoring case and non-alphanumeric characters in Swift

1 Answer

0 votes
import Foundation

func isPalindrome(_ s: String) -> Bool {
    // Remove non-alphanumeric characters and convert to lowercase
    let pattern = "[^a-zA-Z0-9]"
    let regex = try! NSRegularExpression(pattern: pattern)
    let range = NSRange(location: 0, length: s.utf16.count)
    let cleaned = regex.stringByReplacingMatches(in: s, options: [], range: range, withTemplate: "").lowercased()
    
    print(cleaned)
    
    // Check if the string is equal to its reverse
    return cleaned == String(cleaned.reversed())
}


let s = "+^-Ab#c!D 50...#  05*()dcB[]A##@!$"

print(isPalindrome(s))




/*
run:

abcd5005dcba
true

*/

 



answered Aug 10, 2025 by avibootz
...