iOS 正则匹配&类SQL匹配

NSRegularExpression与NSPredicate都是查询匹配字符串处理的,可是NSPredicate支持的是相似SQL语句的查询,支持类SQL类型的查询,好比NSDate,固然,这并不意味这NSPredicate能够彻底取代NSRegularExpression,由于NSRegularExpression的可扩展性更高。html


1.NSRegularExpression的用法

官方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];
}
2.NSPredicate的用法

官方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];
相关文章
相关标签/搜索