前言:在表單驗證中我們經常會用到正則,因為需要用它來判斷使用者輸入的字元是否合法,若不合法則提示錯誤、不讓提交至伺服器;同時也能透過正則從輸入字串中過濾並取得特定部分。總的來說,正則表達式非常強大。
用它判斷使用者輸入的字串是否合法:
// 編寫正則:只能是數字或英文,或兩者皆有
NSString *regex = @"^[a-z0-9A-Z]*$";
// 建立謂詞並設定條件運算式
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
NSString *str = @"Hello100";
if ([predicate evaluateWithObject:str]) {
NSLog(@"Match");
}
字串 Hello100 符合規則,因此會輸出「Match」;若換成其他字元(如「-、=」)則不會有任何輸出。
使用 rangeOfString:options: 方法:
NSString *phoneNo = @"13143503442";
NSRange range = [phoneNo rangeOfString:@"^1[3]\\d{9}$" options:NSRegularExpressionSearch];
if (range.location != NSNotFound) {
NSLog(@"%@", [phoneNo substringWithRange:range]);
}
rangeOfString:options: 會回傳一個 NSRange 接收匹配範圍,匹配不到時回傳 NSNotFound(NSIntegerMax),因此可用來判斷內容是否符合規則。
用來過濾並取得特定部分:
NSString *url = @"1229436624@qq.com";
NSError *error;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[^@]*\\." options:0 error:&error];
if (!error) {
NSTextCheckingResult *match = [regex firstMatchInString:url options:0 range:NSMakeRange(0, [url length])];
if (match) {
NSString *result = [url substringWithRange:match.range];
NSLog(@"%@", result);
}
} else {
NSLog(@"error - %@", error);
}
此例從字串中檢索以「@」開頭、「.」結尾的區間,最終輸出結果為「qq.」。
當一個字串有多個符合規則的字元時,可分別取得:
NSString *regex = @"\\-\\d*\\.";
NSString *str = @"-34023242.-34203020.";
NSError *error;
NSRegularExpression *regular = [NSRegularExpression regularExpressionWithPattern:regex options:NSRegularExpressionCaseInsensitive error:&error];
NSArray *matches = [regular matchesInString:str options:0 range:NSMakeRange(0, str.length)];
for (NSTextCheckingResult *match in matches) {
NSRange range = [match range];
NSString *mStr = [str substringWithRange:range];
NSLog(@"%@", mStr);
}
輸出結果:
-34023242. -34203020.
總結:一般判斷輸入字元是否合法,使用方法一即可;若需擷取特定內容,可用方法二或方法三;若可能有多個擷取結果,則使用方法四。
最後附上正則表達式常用元字符:
摘自百度百科:正則表達式
博文作者:GarveyCalvin
博文出處:https://www.cnblogs.com/GarveyCalvin