天天看點

IOS用正規表達式驗證textfield輸入的内容是否合法

iphone 4.0以後就開始支援正規表達式的使用了,在ios4.0中正規表達式的使用是使用NSRegularExpression類來調用。

1. 下面一個簡單的使用正規表達式的一個例子:NSRegularExpression 類

-(void)parseString{

//組裝一個字元串,需要把裡面的網址解析出來

NSString *urlString=@"sfdsfhttp://www.baidu.com";

//NSRegularExpression類裡面調用表達的方法需要傳遞一個NSError的參數。下面定義一個

 NSError *error;

//http+:[^\\s]* 這個表達式是檢測一個網址的。

    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"http+:[^\\s]*" options:0 error:&error];

   if (regex != nil) {

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

   if (firstMatch) {

      NSRange resultRange = [firstMatch rangeAtIndex:0]; //等同于 firstMatch.range --- 相比對的範圍

      //從urlString當中截取資料

   NSString *result=[urlString substringWithRange:resultRange];

   //輸出結果

   NSLog(@"%@",result);

   }

}

2.使用正規表達式來判斷

//初始化一個NSRegularExpression 對象,并設定檢測對象範圍為:0-9 

NSRegularExpression *regex2 = [NSRegularExpression regularExpressionWithPattern:@"^[0-9]*$" options:0 error:nil];

        if (regex2)

        {//對象進行比對

             NSTextCheckingResult *result2 = [regex2 firstMatchInString:textField.text options:0 range:NSMakeRange(0, [textField.text length])];

            if (result2)  {

            }

<dl><dd></dd></dl>

1。 判斷郵箱格式是否正确的代碼:NSPredicatel類

//利用正規表達式驗證

NSPredicatel類:主要用來指定過濾器的條件,該對象可以準确的描述所需條件,對每個對象通過謂詞進行篩選,判斷是否與條件相比對。謂詞是指在計算機中表示計算真假值的函數。原理和用法都類似于SQL查詢中的where,作用相當于資料庫的過濾取。主要用于從集合中分揀出符合條件的對象,也可以用于字元串的正則比對

-(BOOL)isValidateEmail:(NSString *)email

{

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

    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES%@",emailRegex];

    return [emailTest evaluateWithObject:email];

<dl></dl>

<dd></dd>

2 。 比對9-15個由字母/數字組成的字元串的正規表達式:

    NSString * regex = @"^[A-Za-z0-9]{9,15}$";

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

    BOOL isMatch = [pred evaluateWithObject:txtfldPhoneNumber.text];

Cocoa用NSPredicate描述查詢的方式,原理類似于在資料庫中進行查詢

用BETWEEN,IN,BEGINWITH,ENDWITH,CONTAINS,LIKE這些謂詞來構造NSPredicate,必要的時候使用SELF直接對自己進行比對

[cpp]

//基本的查詢  

NSPredicate *predicate; 

predicate = [NSPredicate predicateWithFormat: @"name == 'Herbie'"]; 

    BOOL match = [predicate evaluateWithObject: car]; 

    NSLog (@"%s", (match) ? "YES" : "NO"); 

//在整個cars裡面循環比較  

    predicate = [NSPredicate predicateWithFormat: @"engine.horsepower &gt; 150"]; 

    NSArray *cars = [garage cars]; 

    for (Car *car in [garage cars]) { 

        if ([predicate evaluateWithObject: car]) { 

            NSLog (@"%@", car.name); 

        } 

    } 

//輸出完整的資訊  

    NSArray *results; 

    results = [cars filteredArrayUsingPredicate: predicate]; 

    NSLog (@"%@", results); 

//含有變量的謂詞  

    NSPredicate *predicateTemplate = [NSPredicate predicateWithFormat:@"name == $NAME"]; 

    NSDictionary *varDict; 

    varDict = [NSDictionary dictionaryWithObjectsAndKeys: 

               @"Herbie", @"NAME", nil]; 

    predicate = [predicateTemplate predicateWithSubstitutionVariables: varDict]; 

    NSLog(@"SNORGLE: %@", predicate); 

    match = [predicate evaluateWithObject: car]; 

  NSLog (@"%s", (match) ? "YES" : "NO"); 

//注意不能使用$VARIABLE作為路徑名,因為它值代表值  

    predicate = [NSPredicate predicateWithFormat: 

                 @"(engine.horsepower &gt; 50) AND (engine.horsepower &lt; 200)"]; 

    NSLog (@"oop %@", results); 

    predicate = [NSPredicate predicateWithFormat: @"name &lt; 'Newton'"]; 

    NSLog (@"%@", [results valueForKey: @"name"]); 

//強大的數組運算符  

                 @"engine.horsepower BETWEEN { 50, 200 }"]; 

    NSArray *betweens = [NSArray arrayWithObjects: 

                         [NSNumber numberWithInt: 50], [NSNumber numberWithInt: 200], nil]; 

    predicate = [NSPredicate predicateWithFormat: @"engine.horsepower BETWEEN %@", betweens]; 

    predicateTemplate = [NSPredicate predicateWithFormat: @"engine.horsepower BETWEEN $POWERS"]; 

    varDict = [NSDictionary dictionaryWithObjectsAndKeys: betweens, @"POWERS", nil]; 

//IN運算符  

    predicate = [NSPredicate predicateWithFormat: @"name IN { 'Herbie', 'Snugs', 'Badger', 'Flap' }"]; 

    predicate = [NSPredicate predicateWithFormat: @"SELF.name IN { 'Herbie', 'Snugs', 'Badger', 'Flap' }"]; 

    names = [cars valueForKey: @"name"]; 

    predicate = [NSPredicate predicateWithFormat: @"SELF IN { 'Herbie', 'Snugs', 'Badger', 'Flap' }"]; 

    results = [names filteredArrayUsingPredicate: predicate];//這裡限制了SELF的範圍  

//BEGINSWITH,ENDSWITH,CONTAINS  

//附加符号,[c],[d],[cd],c表示不區分大小寫,d表示不區分發音字元,cd表示什麼都不區分  

    predicate = [NSPredicate predicateWithFormat: @"name BEGINSWITH 'Bad'"]; 

    predicate = [NSPredicate predicateWithFormat: @"name BEGINSWITH 'HERB'"]; 

    predicate = [NSPredicate predicateWithFormat: @"name BEGINSWITH[cd] 'HERB'"]; 

//LIKE運算符(通配符)  

    predicate = [NSPredicate predicateWithFormat: @"name LIKE[cd] '*er*'"]; 

    predicate = [NSPredicate predicateWithFormat: @"name LIKE[cd] '???er*'"]; 

//基本的查詢

NSPredicate *predicate;

predicate = [NSPredicate predicateWithFormat: @"name == 'Herbie'"];

    BOOL match = [predicate evaluateWithObject: car];

    NSLog (@"%s", (match) ? "YES" : "NO");

//在整個cars裡面循環比較

    predicate = [NSPredicate predicateWithFormat: @"engine.horsepower &gt; 150"];

    NSArray *cars = [garage cars];

    for (Car *car in [garage cars]) {

        if ([predicate evaluateWithObject: car]) {

            NSLog (@"%@", car.name);

        }

    }

//輸出完整的資訊

    NSArray *results;

    results = [cars filteredArrayUsingPredicate: predicate];

    NSLog (@"%@", results);

//含有變量的謂詞

    NSPredicate *predicateTemplate = [NSPredicate predicateWithFormat:@"name == $NAME"];

    NSDictionary *varDict;

    varDict = [NSDictionary dictionaryWithObjectsAndKeys:

               @"Herbie", @"NAME", nil];

    predicate = [predicateTemplate predicateWithSubstitutionVariables: varDict];

    NSLog(@"SNORGLE: %@", predicate);

    match = [predicate evaluateWithObject: car];

  NSLog (@"%s", (match) ? "YES" : "NO");

//注意不能使用$VARIABLE作為路徑名,因為它值代表值

//謂詞字元竄還支援c語言中一些常用的運算符

    predicate = [NSPredicate predicateWithFormat:

                 @"(engine.horsepower &gt; 50) AND (engine.horsepower &lt; 200)"];

    NSLog (@"oop %@", results);

    predicate = [NSPredicate predicateWithFormat: @"name &lt; 'Newton'"];

    NSLog (@"%@", [results valueForKey: @"name"]);

//強大的數組運算符

                 @"engine.horsepower BETWEEN { 50, 200 }"];

    NSArray *betweens = [NSArray arrayWithObjects:

                         [NSNumber numberWithInt: 50], [NSNumber numberWithInt: 200], nil];

    predicate = [NSPredicate predicateWithFormat: @"engine.horsepower BETWEEN %@", betweens];

    predicateTemplate = [NSPredicate predicateWithFormat: @"engine.horsepower BETWEEN $POWERS"];

    varDict = [NSDictionary dictionaryWithObjectsAndKeys: betweens, @"POWERS", nil];

//IN運算符

    predicate = [NSPredicate predicateWithFormat: @"name IN { 'Herbie', 'Snugs', 'Badger', 'Flap' }"];

    predicate = [NSPredicate predicateWithFormat: @"SELF.name IN { 'Herbie', 'Snugs', 'Badger', 'Flap' }"];

    names = [cars valueForKey: @"name"];

    predicate = [NSPredicate predicateWithFormat: @"SELF IN { 'Herbie', 'Snugs', 'Badger', 'Flap' }"];

    results = [names filteredArrayUsingPredicate: predicate];//這裡限制了SELF的範圍

//BEGINSWITH,ENDSWITH,CONTAINS

//附加符号,[c],[d],[cd],c表示不區分大小寫,d表示不區分發音字元,cd表示什麼都不區分

    predicate = [NSPredicate predicateWithFormat: @"name BEGINSWITH 'Bad'"];

    predicate = [NSPredicate predicateWithFormat: @"name BEGINSWITH 'HERB'"];

    predicate = [NSPredicate predicateWithFormat: @"name BEGINSWITH[cd] 'HERB'"];

//LIKE運算符(通配符)

    predicate = [NSPredicate predicateWithFormat: @"name LIKE[cd] '*er*'"];

    predicate = [NSPredicate predicateWithFormat: @"name LIKE[cd] '???er*'"];

本文轉蓬萊仙羽51CTO部落格,原文連結:http://blog.51cto.com/dingxiaowei/1366430

,如需轉載請自行聯系原作者