简体   繁体   English

如何检查 Swift 字符串是否只包含某些字符?

[英]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:我有一个字符串,我想检查它是否只包含大小写的 26 个字母字符和 10 个数字字符:

abcdefghijklmnopkrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789

How can I check that a string does not contain any special characters?如何检查字符串不包含任何特殊字符?

Use

if string.range(of: "^[a-zA-Z0-9]*$", options: .regularExpression) != nil as mentioned by @sulthan. if string.range(of: "^[a-zA-Z0-9]*$", options: .regularExpression) != nil如@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例如,^P 是正则表达式匹配字符串开头的字母 P

  2. * Regex followed by * will handle repetition in a regex. *正则表达式后跟 * 将处理正则表达式中的重复。 For example P* Matches PPP or P. This will matches the empty string also.例如 P* 匹配 PPP 或 P。这也将匹配空字符串。

  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.例如,P$ regex 将匹配字符串末尾的 P。

Use + instead of * if you want to avoid empty string.如果您想避免空字符串,请使用+而不是* "^[a-zA-Z0-9]+$" as mentioned by vadian "^[a-zA-Z0-9]+$"vadian所述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM