NSRegularExpression與NSPredicate都是查詢匹配字符串處理的,可是NSPredicate支持的是相似SQL語句的查詢,支持類SQL類型的查詢,好比NSDate,固然,這並不意味這NSPredicate能夠徹底取代NSRegularExpression,由於NSRegularExpression的可擴展性更高。html
官方Doc:NSRegularExpression java
來個例子,網頁圖片採集正則表達式
NSError *error; NSString *strRegex = @"<img([^<]+)(/>|</img>)"; NSRegularExpression *reg = [NSRegularExpression regularExpressionWithPattern:strRegex options:NSRegularExpressionCaseInsensitive|NSRegularExpressionDotMatchesLineSeparators error:&error]; //無視大小寫. NSArray *matches = [reg matchesInString:@"所要查找的字符串" options:NSMatchingCompleted range:NSMakeRange(0, [muStrHTMLContent length])]; for (NSTextCheckingResult *match in matches) { i++; NSRange range = [match range]; NSLog(@"%d,%d,%@",range.location,range.length,[muStrCloneHTMLContent substringWithRange:range]); } -------------------------------------------------------------------------------------------------------------------- //組裝一個字符串,須要把裏面的網址解析出來 NSString *urlString=@"<meta/><link/><title>1Q84 BOOK1</title></head><body>"; //NSRegularExpression類裏面調用表達的方法須要傳遞一個NSError的參數。下面定義一個 NSError *error; //error主要是用來記錄錯誤信息,這裏不須要初始化 //http+:[^\\s]* 這個表達式是檢測一個網址的。(?<=title\>).*(?=</title)截取html文章中的<title></title>中內文字的正則表達式 NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(?<=title\\>).*(?=</title)" options:0 error:&error]; if (regex != nil) { NSTextCheckingResult *firstMatch=[regex firstMatchInString:urlString options:0 range:NSMakeRange(0, [urlString length])]; if (firstMatch) { NSRange resultRange = [firstMatch rangeAtIndex:0]; //從urlString當中截取數據 NSString *result=[urlString substringWithRange:resultRange]; //輸出結果 NSLog(@"->%@<-",result); } }
固然也能夠以下:
數據庫
__block NSUInteger count = 0; [regex enumerateMatchesInString:string options:0 range:NSMakeRange(0, [string length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){ NSRange matchRange = [match range]; NSRange firstHalfRange = [match rangeAtIndex:1]; NSRange secondHalfRange = [match rangeAtIndex:2]; if (++count >= 100) *stop = YES; }]; -------------------------------------------------------------------------------------- NSRange rangeOfFirstMatch = [regex rangeOfFirstMatchInString:string options:0 range:NSMakeRange(0, [string length])]; if (!NSEqualRanges(rangeOfFirstMatch, NSMakeRange(NSNotFound, 0))) { NSString *substringForFirstMatch = [string substringWithRange:rangeOfFirstMatch]; }
官方Doc:NSPredicate數組
Cocoa用NSPredicate描述查詢的方式,原理相似於在數據庫中進行查詢 計算謂詞: //基本的查詢 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);
匹配NSDateapp
//日期在十天以內: NSDate *endDate = [[NSDate date] retain]; NSTimeInterval timeInterval= [endDate timeIntervalSinceReferenceDate]; timeInterval -=3600*24*10; NSDate *beginDate = [[NSDate dateWithTimeIntervalSinceReferenceDate:timeInterval] retain]; //對coredata進行篩選(假設有fetchRequest) NSPredicate *predicate_date = [NSPredicate predicateWithFormat:@"date >= %@ AND date <= %@", beginDate,endDate]; [fetchRequest setPredicate:predicate_date]; //釋放retained的對象 [endDate release]; [beginDate release];