iOS中使用RegexNSRegularExpression 來驗證textfiled輸入的內容_Regex

來源:互聯網
上載者:User

何謂Regex

Regex(regular expression),在電腦科學中,是指一個用來描述或者匹配一系列符合某個句法規則的字串的單個字串。在很多文字編輯器或其他工具裡,Regex通常被用來檢索和/或替換那些符合某個模式的常值內容。Regex這個概念最初是由Unix中的工具軟體(例如sed和grep)普及開的。Regex通常縮寫成“regex”,單數有regexp、regex,複數有regexps、regexes、regexen。

Regex組成

Regex有兩種類型的字元組成

第一種:用來匹配的字元,或者叫常規字元

第二種:控制字元或具有特殊含義的元字元

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

1. 下面一個簡單的使用Regex的一個例子: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.使用Regex來判斷

//初始化一個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) {      }}

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

//利用Regex驗證

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];}

2.匹配9-15個由字母/數字組成的字串的Regex:

  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直接對自己進行匹配

//基本的查詢 NSPredicate *predicate; predicate = [NSPredicate predicateWithFormat: @"name == 'Herbie'"];   BOOL match = [predicate evaluateWithObject: car];   NSLog (@"%s", (match) ? "YES" : "NO"); //在整個cars裡面迴圈比較   predicate = [NSPredicate predicateWithFormat: @"engine.horsepower > 150"];   NSArray *cars = [garage cars];   for (Car *car in [garage cars]) {     if ([predicate evaluateWithObject: car]) {       NSLog (@"%@", car.name);     }   } //輸出完整的資訊   predicate = [NSPredicate predicateWithFormat: @"engine.horsepower > 150"];   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 > 50) AND (engine.horsepower < 200)"];   results = [cars filteredArrayUsingPredicate: predicate];   NSLog (@"oop %@", results);   predicate = [NSPredicate predicateWithFormat: @"name < 'Newton'"];   results = [cars filteredArrayUsingPredicate: predicate];   NSLog (@"%@", [results valueForKey: @"name"]); //強大的數組運算子   predicate = [NSPredicate predicateWithFormat:          @"engine.horsepower BETWEEN { 50, 200 }"];   results = [cars filteredArrayUsingPredicate: predicate];   NSLog (@"%@", results);   NSArray *betweens = [NSArray arrayWithObjects:              [NSNumber numberWithInt: 50], [NSNumber numberWithInt: 200], nil];   predicate = [NSPredicate predicateWithFormat: @"engine.horsepower BETWEEN %@", betweens];   results = [cars filteredArrayUsingPredicate: predicate];   NSLog (@"%@", results);   predicateTemplate = [NSPredicate predicateWithFormat: @"engine.horsepower BETWEEN $POWERS"];   varDict = [NSDictionary dictionaryWithObjectsAndKeys: betweens, @"POWERS", nil];   predicate = [predicateTemplate predicateWithSubstitutionVariables: varDict];   results = [cars filteredArrayUsingPredicate: predicate];   NSLog (@"%@", results); //IN運算子   predicate = [NSPredicate predicateWithFormat: @"name IN { 'Herbie', 'Snugs', 'Badger', 'Flap' }"];   results = [cars filteredArrayUsingPredicate: predicate];   NSLog (@"%@", [results valueForKey: @"name"]);   predicate = [NSPredicate predicateWithFormat: @"SELF.name IN { 'Herbie', 'Snugs', 'Badger', 'Flap' }"];   results = [cars filteredArrayUsingPredicate: predicate];   NSLog (@"%@", [results valueForKey: @"name"]);   names = [cars valueForKey: @"name"];   predicate = [NSPredicate predicateWithFormat: @"SELF IN { 'Herbie', 'Snugs', 'Badger', 'Flap' }"];   results = [names filteredArrayUsingPredicate: predicate];//這裡限制了SELF的範圍   NSLog (@"%@", results); //BEGINSWITH,ENDSWITH,CONTAINS //附加符號,[c],[d],[cd],c表示不區分大小寫,d表示不區分發音字元,cd表示什麼都不區分   predicate = [NSPredicate predicateWithFormat: @"name BEGINSWITH 'Bad'"];   results = [cars filteredArrayUsingPredicate: predicate];   NSLog (@"%@", results);   predicate = [NSPredicate predicateWithFormat: @"name BEGINSWITH 'HERB'"];   results = [cars filteredArrayUsingPredicate: predicate];   NSLog (@"%@", results);   predicate = [NSPredicate predicateWithFormat: @"name BEGINSWITH[cd] 'HERB'"];   results = [cars filteredArrayUsingPredicate: predicate];   NSLog (@"%@", results); //LIKE運算子(萬用字元)   predicate = [NSPredicate predicateWithFormat: @"name LIKE[cd] '*er*'"];   results = [cars filteredArrayUsingPredicate: predicate];   NSLog (@"%@", results);   predicate = [NSPredicate predicateWithFormat: @"name LIKE[cd] '???er*'"];   results = [cars filteredArrayUsingPredicate: predicate];   NSLog (@"%@", results); //基本的查詢NSPredicate *predicate;predicate = [NSPredicate predicateWithFormat: @"name == 'Herbie'"];  BOOL match = [predicate evaluateWithObject: car];  NSLog (@"%s", (match) ? "YES" : "NO");//在整個cars裡面迴圈比較  predicate = [NSPredicate predicateWithFormat: @"engine.horsepower > 150"];  NSArray *cars = [garage cars];  for (Car *car in [garage cars]) {    if ([predicate evaluateWithObject: car]) {      NSLog (@"%@", car.name);    }  }//輸出完整的資訊  predicate = [NSPredicate predicateWithFormat: @"engine.horsepower > 150"];  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 > 50) AND (engine.horsepower < 200)"];  results = [cars filteredArrayUsingPredicate: predicate];  NSLog (@"oop %@", results);  predicate = [NSPredicate predicateWithFormat: @"name < 'Newton'"];  results = [cars filteredArrayUsingPredicate: predicate];  NSLog (@"%@", [results valueForKey: @"name"]);//強大的數組運算子  predicate = [NSPredicate predicateWithFormat:         @"engine.horsepower BETWEEN { 50, 200 }"];  results = [cars filteredArrayUsingPredicate: predicate];  NSLog (@"%@", results);  NSArray *betweens = [NSArray arrayWithObjects:             [NSNumber numberWithInt: 50], [NSNumber numberWithInt: 200], nil];  predicate = [NSPredicate predicateWithFormat: @"engine.horsepower BETWEEN %@", betweens];  results = [cars filteredArrayUsingPredicate: predicate];  NSLog (@"%@", results);  predicateTemplate = [NSPredicate predicateWithFormat: @"engine.horsepower BETWEEN $POWERS"];  varDict = [NSDictionary dictionaryWithObjectsAndKeys: betweens, @"POWERS", nil];  predicate = [predicateTemplate predicateWithSubstitutionVariables: varDict];  results = [cars filteredArrayUsingPredicate: predicate];  NSLog (@"%@", results);//IN運算子  predicate = [NSPredicate predicateWithFormat: @"name IN { 'Herbie', 'Snugs', 'Badger', 'Flap' }"];  results = [cars filteredArrayUsingPredicate: predicate];  NSLog (@"%@", [results valueForKey: @"name"]);  predicate = [NSPredicate predicateWithFormat: @"SELF.name IN { 'Herbie', 'Snugs', 'Badger', 'Flap' }"];  results = [cars filteredArrayUsingPredicate: predicate];  NSLog (@"%@", [results valueForKey: @"name"]);  names = [cars valueForKey: @"name"];  predicate = [NSPredicate predicateWithFormat: @"SELF IN { 'Herbie', 'Snugs', 'Badger', 'Flap' }"];  results = [names filteredArrayUsingPredicate: predicate];//這裡限制了SELF的範圍  NSLog (@"%@", results);//BEGINSWITH,ENDSWITH,CONTAINS//附加符號,[c],[d],[cd],c表示不區分大小寫,d表示不區分發音字元,cd表示什麼都不區分  predicate = [NSPredicate predicateWithFormat: @"name BEGINSWITH 'Bad'"];  results = [cars filteredArrayUsingPredicate: predicate];  NSLog (@"%@", results);  predicate = [NSPredicate predicateWithFormat: @"name BEGINSWITH 'HERB'"];  results = [cars filteredArrayUsingPredicate: predicate];  NSLog (@"%@", results);  predicate = [NSPredicate predicateWithFormat: @"name BEGINSWITH[cd] 'HERB'"];  results = [cars filteredArrayUsingPredicate: predicate];  NSLog (@"%@", results);//LIKE運算子(萬用字元)  predicate = [NSPredicate predicateWithFormat: @"name LIKE[cd] '*er*'"];  results = [cars filteredArrayUsingPredicate: predicate];  NSLog (@"%@", results);  predicate = [NSPredicate predicateWithFormat: @"name LIKE[cd] '???er*'"];  results = [cars filteredArrayUsingPredicate: predicate];  NSLog (@"%@", results);

以上就是小編給大家分享的iOS中使用RegexNSRegularExpression 來驗證textfiled輸入的內容,希望大家喜歡。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.