NSPredicate 常用正则
2017-04-05 本文已影响22人
JaiUnChat
1.验证邮箱
func isEmail(_ email: String) -> Bool {
let regex = "[A-Z0-9a-z._% -] @[A-Za-z0-9.-] \\.[A-Za-z]{2,4}"
let predicate = NSPredicate(format: "SELF MATCHES %@", regex)
return predicate.evaluate(with: email)
}
2.验证手机号
func isMobieNumber(_ phoneNumber: String) -> Bool {
// 用枚举改写一下效率会高很多
let chinaMobie = "^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$"
let chinaUnicom = "^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$"
let chinaTelecom = "^1(3[0-2]|5[256]|8[56])\\d{8}$"
let telephone = "^1((33|53|8[09])[0-9]|349)\\d{7}$"
let isChinaMobie = NSPredicate(format: "SELF MATCH %@", chinaMobie)
let isChinaUnicom = NSPredicate(format: "SELF MATCH %@", chinaUnicom)
let isChinaTelecom = NSPredicate(format: "SELF MATCH %@", chinaTelecom)
let isTelephone = NSPredicate(format: "SELF MATCH %@", telephone)
if isChinaMobie.evaluate(with: phoneNumber) == true || isChinaUnicom.evaluate(with: phoneNumber) == true || isChinaTelecom.evaluate(with: phoneNumber) == true || isTelephone.evaluate(with: phoneNumber) == true {
return true
} else {
return false
}
}
3.验证车牌号
func isLicenseNumber(_ number: String) -> Bool {
let regex = "^[A-Za-z]{1}[A-Za-z_0-9]{5}$"
let predicate = NSPredicate(format: "SELF MATCHES %@", regex)
return perdicate.evaluate(with: number)
}
4.验证用户名
func isUserName(_ name: String) -> Bool {
let regex = "^[A-Za-z0-9]{6,20}+$"
let predicate = NSPredicate(format: "SELF MATCHES %@", regex)
return predicate.evaluate(with: name)
}
5.验证密码
func isPassword(_ passWord: String) -> Bool {
let regex = "^[a-zA-Z0-9]{6,20}+$"
let predicate = NSPredicate(format: "SELF MATCHES%@", regex)
return predicate.evaluate(with: passWord)
}
6.验证中文
func isChinese(_ chinese: String) -> Bool {
let regex = "^[\u{4e00}-\u{9fa5}]{4,8}$" // 4-8位
let predicate = NSPredicate(format: "SELF MATCHES%@", regex)
return predicate.evaluate(with: chinese)
}