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, #1100@ ! ^&Programming (*).";
 
s = removeNonAlphanumeric(from: s)
 
print(s) 
 
 
 
/*
run:
 
Swift1100Programming

*/

 



answered Jan 29, 2025 by avibootz
edited 1 day ago by avibootz

Related questions

...