我正在尝试创建一个函数来验证我的字符串是否使用这种格式
ABC123
First three characters should be letters and the other 3 should be numbers
我不知道如何开始
谢谢
最佳答案
你可以用字符串的正则表达式匹配来做到这一点,就像这样:
let str = "ABC123"
let optRange = str.rangeOfString("^[A-Za-z]{3}\\d{3}$", options: .RegularExpressionSearch)
if let range = optRange {
println("Matched")
} else {
println("Not matched")
}
上面的正则表达式要求匹配占据整个字符串(两端的 ^
和 $
anchor ),具有三个字母 [A-Za-z ]{3}
和三位数字 \\d{3}
。
如果您愿意,您也可以将它用作扩展:
extension String {
var match: Bool {
return rangeOfString("^[A-Za-z]{3}\\d{3}$", options: .RegularExpressionSearch) != nil
}
}
"ABC123".match // true
关于ios - 在 Swift 中检查字符串是否为 3 个字符和 3 个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28654695/