iOS正則表達式《2》

  1. iOS 中可以通過 NSPredicate 來處理正則表達式。相關資料如下:

    NSPredicate 蘋果官方文檔:
    http://developer.apple.com/documentation/Cocoa/Conceptual/Predicates/predicates.html

    Predicate format strings:
    http://developer.apple.com/documentation/Cocoa/Conceptual/Predicates/Articles/pSyntax.html

    ICU 正則表達式規則:
    http://www.icu-project.org/userguide/regexp.html


    在 iOS 中,我們使用 NSPredicate 的字符串比較功能來進行正則表達式處理,其比較關鍵字爲:MATCHES

    下面,列舉一個匹配6-15個由字母/數字組成的字符串的正則表達式,來看看 NSPredicate 的具體使用:

    1. NSString * regex        = @"(^[A-Za-z0-9]{6,15}$)";  
    2. NSPredicate * pred      = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];  
    3. BOOL isMatch            = [pred evaluateWithObject:@"123456ABCde"];  

    下面是一些常用的正則表達式
  2. //郵箱  
  3. + (BOOL) validateEmail:(NSString *)email  
  4. {  
  5.     NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";  
  6.     NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];  
  7.     return [emailTest evaluateWithObject:email];  
  8. }  
  9.   
  10.   
  11. //手機號碼驗證  
  12. + (BOOL) validateMobile:(NSString *)mobile  
  13. {  
  14.     //手機號以13, 15,18開頭,八個 \d 數字字符  
  15.     NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";  
  16.     NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];  
  17.     return [phoneTest evaluateWithObject:mobile];  
  18. }  
  19.   
  20.   
  21. //車牌號驗證  
  22. + (BOOL) validateCarNo:(NSString *)carNo  
  23. {  
  24.     NSString *carRegex = @"^[\u4e00-\u9fa5]{1}[a-zA-Z]{1}[a-zA-Z_0-9]{4}[a-zA-Z_0-9_\u4e00-\u9fa5]$";  
  25.     NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",carRegex];  
  26.     NSLog(@"carTest is %@",carTest);  
  27.     return [carTest evaluateWithObject:carNo];  
  28. }  
  29.   
  30.   
  31. //車型  
  32. + (BOOL) validateCarType:(NSString *)CarType  
  33. {  
  34.     NSString *CarTypeRegex = @"^[\u4E00-\u9FFF]+$";  
  35.     NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",CarTypeRegex];  
  36.     return [carTest evaluateWithObject:CarType];  
  37. }  
  38.   
  39.   
  40. //用戶名  
  41. + (BOOL) validateUserName:(NSString *)name  
  42. {  
  43.     NSString *userNameRegex = @"^[A-Za-z0-9]{6,20}+$";  
  44.     NSPredicate *userNamePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",userNameRegex];  
  45.     BOOL B = [userNamePredicate evaluateWithObject:name];  
  46.     return B;  
  47. }  
  48.   
  49.   
  50. //密碼  
  51. + (BOOL) validatePassword:(NSString *)passWord  
  52. {  
  53.     NSString *passWordRegex = @"^[a-zA-Z0-9]{6,20}+$";  
  54.     NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passWordRegex];  
  55.     return [passWordPredicate evaluateWithObject:passWord];  
  56. }  
  57.   
  58.   
  59. //暱稱  
  60. + (BOOL) validateNickname:(NSString *)nickname  
  61. {  
  62.     NSString *nicknameRegex = @"^[\u4e00-\u9fa5]{4,8}$";  
  63.     NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",nicknameRegex];  
  64.     return [passWordPredicate evaluateWithObject:nickname];  
  65. }  
  66.   
  67.   
  68. //身份證號  
  69. + (BOOL) validateIdentityCard: (NSString *)identityCard  
  70. {  
  71.     BOOL flag;  
  72.     if (identityCard.length <= 0) {  
  73.         flag = NO;  
  74.         return flag;  
  75.     }  
  76.     NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";  
  77.     NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];  
  78.     return [identityCardPredicate evaluateWithObject:identityCard];  
  79. }  

其實iOS中有三種方式來實現正則表達式的匹配。現在將他們都記錄在這裏:

1.利用NSPredicate(謂詞)匹配

例如匹配有效郵箱:

NSString *email = @“[email protected]”;

    NSString *regex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];

    BOOL isValid = [predicate evaluateWithObject:email];

謂詞匹配比較靈活,但是需要有謂詞的相關知識。


2.利用rangeOfString:option:直接查找


    NSString *searchText = @"// Do any additional setup after loading the view, typically from a nib.";

    NSRange range = [searchText rangeOfString:@"(?:[^,])*\\." options:NSRegularExpressionSearch];

    if (range.location != NSNotFound) {

        NSLog(@"%@", [searchText substringWithRange:range]);

    }

options中設定NSRegularExpressionSearch就是表示利用正則表達式匹配,會返回第一個匹配結果的位置。


3.使用正則表達式類


    NSString *searchText = @"// Do any additional setup after loading the view, typically from a nib.";    

    NSError *error = NULL;

    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(?:[^,])*\\." options:NSRegularExpressionCaseInsensitive error:&error];

    NSTextCheckingResult *result = [regex firstMatchInString:searchText options:0 range:NSMakeRange(0, [searchText length])];

    if (result) {

        NSLog(@"%@\n", [searchText substringWithRange:result.range]);

    }

使用系統的正則表達式類(NSRegularExpression)會返回匹配的多個結果。


小結:

第一種匹配需要學習NSPredicate的寫法,需要查閱蘋果相關技術文檔;如果只關心第一個匹配的結果,第二種匹配較爲簡潔;如果需要匹配多個結果,同時匹配多次,第三種方式效率會更高。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章