Check if string contains special characters in Swift

后端 未结 10 2053
时光取名叫无心
时光取名叫无心 2020-12-12 18:20

I have to detect whether a string contains any special characters. How can I check it? Does Swift support regular expressions?

var characterSet:NSCharacterSet         


        
10条回答
  •  忘掉有多难
    2020-12-12 19:01

    @Martin R answer is great, I just wanted to update it (the second part) to Swift 2.1 version

    let regex = try! NSRegularExpression(pattern: ".*[^A-Za-z0-9].*", options: NSRegularExpressionOptions())
    if regex.firstMatchInString(searchTerm!, options: NSMatchingOptions(), range:NSMakeRange(0, searchTerm!.characters.count)) != nil {
        print("could not handle special characters")
    }
    

    I used try! as we can be sure it create a regex, it doesn't base on any dynamic kind of a data

提交回复
热议问题