Search code examples
swiftstringspecial-characterscontains

How to check if Swift string contains only certain characters?


I have a string and I want to check if it only contains the the 26 alphabetical characters, in upper and lower case, and the 10 number characters:

abcdefghijklmnopkrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789

How can I check that a string does not contain any special characters?


Solution

  • Use

    if string.range(of: "^[a-zA-Z0-9]*$", options: .regularExpression) != nil as mentioned by @sulthan.

    1. ^ is the starting point of regex. This does not match any character. For example, ^P is regex matching letter P at the beginning of the String

    2. * Regex followed by * will handle repetition in a regex. For example P* Matches PPP or P. This will matches the empty string also.

    3. $ is the end of the string. This does not match any character. For example, P$ regex will match P at the end of the string.

    Use + instead of * if you want to avoid empty string. "^[a-zA-Z0-9]+$" as mentioned by vadian