Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if string contains special characters in Swift

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

var characterSet:NSCharacterSet = NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") if (searchTerm!.rangeOfCharacterFromSet(characterSet).location == NSNotFound){     println("Could not handle special characters") } 

I tried the code above, but it matches only if I enter the first character as a special character.

like image 288
iPhone Guy Avatar asked Dec 30 '14 09:12

iPhone Guy


People also ask

Is a special character in Swift?

Special Characters in String Literals String literals can include the following special characters: The escaped special characters \0 (null character), \\ (backslash), \t (horizontal tab), \n (line feed), \r (carriage return), \" (double quotation mark) and \' (single quotation mark)

How do you check if a string contains a set of characters?

While the find and count string methods can check for substring occurrences, there is no ready-made function to check for the occurrence in a string of a set of characters. While working on a condition to check whether a string contained the special characters used in the glob.

How do I remove special characters from a string in Swift?

To remove specific set of characters from a String in Swift, take these characters to be removed in a set, and call the removeAll(where:) method on this string str , with the predicate that if the specific characters contain this character in the String.


1 Answers

Your code check if no character in the string is from the given set. What you want is to check if any character is not in the given set:

if (searchTerm!.rangeOfCharacterFromSet(characterSet.invertedSet).location != NSNotFound){     println("Could not handle special characters") } 

You can also achieve this using regular expressions:

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

The pattern [^A-Za-z0-9] matches a character which is not from the ranges A-Z, a-z, or 0-9.

Update for Swift 2:

let searchTerm = "a+b"  let characterset = NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") if searchTerm.rangeOfCharacterFromSet(characterset.invertedSet) != nil {     print("string contains special characters") } 

Update for Swift 3:

let characterset = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") if searchTerm.rangeOfCharacter(from: characterset.inverted) != nil {     print("string contains special characters") } 
like image 63
Martin R Avatar answered Sep 27 '22 21:09

Martin R