OC版:
//判斷手機號
- (BOOL)checkoutPhoneNum: (NSString *)phoneNum {
NSString *regexStr = @"^1[3,8]\\d{9}|14[5,7,9]\\d{8}|15[^4]\\d{8}|17[^2,4,9]\\d{8}$";
NSError *error;
NSRegularExpression *regular = [NSRegularExpression regularExpressionWithPattern:regexStr options:NSRegularExpressionCaseInsensitive error:&error];
if (error) return NO;
NSInteger count = [regular numberOfMatchesInString:phoneNum options:NSMatchingReportCompletion range:NSMakeRange(0, phoneNum.length)];
if (count > 0) {
return YES;
} else {
return NO;
}
}複製程式碼
Swift(3.0.1):
func checkoutPhoneNum(for regex: String, in phoneNum: String) -> Bool {
do {
let regex = try NSRegularExpression(pattern: regex)
let nsString = phoneNum as NSString
let results = regex.matches(in: phoneNum, range: NSRange(location: 0, length: nsString.length))
let resultArray = results.map { nsString.substring(with: $0.range) }
print(resultArray.count)
if resultArray.count > 0 {
return true
} else {
return false
}
} catch let error {
print("無效正規表示式: \(error.localizedDescription)")
return false
}
}複製程式碼