正则表达式是我们经常要用到的方法,今天我们通过一种简单的自定义操作符来重新认识下正则表达式的最优写法:
precedencegroup MatchPrecedence {
associativity: none
higherThan: DefaultPrecedence
}
infixoperator =~ : MatchPrecedence
/// 正则表达式判断
///
/// - Parameters:
/// - lhs: 左边的参数,内容
/// - rhs: 右边的参数,规则
/// - Returns: 如果符合返回true,否则返回false
func=~(lhs:String, rhs:MMRegExKey) ->Bool{
do{
return try RegexHelper(rhs.rawValue).match(lhs)
}catch_{
return false
}
}
struct RegexHelper {
let regex: NSRegularExpression
init(_pattern:String) throws{
try regex=NSRegularExpression(pattern: pattern,
options: .caseInsensitive)
}
func match(_input:String) ->Bool{
let matches =regex.matches(in: input,
options: [],
range:NSMakeRange(0, input.utf16.count))
return matches.count>0
}
}
struct MMRegExKey: RawRepresentable {
typealias RawValue =String
var rawValue:String
static let phoneNumber = MMRegExKey(rawValue:"^(1[3-9])\\d{9}$")
static let telephone = MMRegExKey(rawValue:"^[0-9]{8}$")
static let smsCode = MMRegExKey(rawValue:"^[0-9]{6}$")
static let paymentCode = MMRegExKey(rawValue:"^[0-9]{6}$")
static let password = MMRegExKey(rawValue:"^[0-9A-Za-z]{6,20}$")
}
使用:
extension String {
/// 检查手机号码格式
///
/// - Throws: 错误原因
func checkPhoneNumber() throws{
guard !self.isEmpty else{
throw NSError(localizedDescription:"请输入手机号码")
}
guard self =~ .phoneNumber else{
throw NSError(localizedDescription:"手机号码输入有误")
}
}
}
网友评论