How to remove all non-alphanumeric characters from a string in Swift

1 Answer

0 votes
import Foundation

func removeNonAlphanumeric(from s: String) -> String {
    let pattern = "[^a-zA-Z0-9]"
    let regex = try! NSRegularExpression(pattern: pattern, options: [])
    let range = NSRange(location: 0, length: s.utf16.count)
    let result = regex.stringByReplacingMatches(in: s, options: [], range: range, withTemplate: "")
    
    return result
}

var s = "Swift, #@ ! ^&Programming (*).";

s = removeNonAlphanumeric(from: s)

print(s) 



/*
run:

SwiftProgramming

*/

 



answered Jan 29, 2025 by avibootz
...