2014-10-19 96 views
0

我寫了一個簡單的方法來檢查給定的數組是否至少有一個字符串,它與提供的模式相匹配......但缺少某些東西,不確定如何將正面結果限制爲全部單詞,而不僅僅是適合模式的第一個子字符串。驗證字符串對給定的正則表達式模式?

+ (BOOL)hasWordsWithPattern:(NSString *)pattern inWords:(NSArray *)words{ 
NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:pattern 
                      options:NSRegularExpressionCaseInsensitive 
                       error:nil]; 
for (NSString *s in words) { 
    if ([expression matchesInString:s 
          options:0 
           range:NSMakeRange(0, s.length)]) { 
     NSLog(@"there is a match!"); 
     return YES; 
    } 
} 
NSLog(@"sorry, no match found!"); 
return NO; 

}

回答

0

我傻,有做的是更簡單的方法:)基於https://stackoverflow.com/a/5777016/1015049

+ (BOOL)hasWordsWithPattern:(NSString *)pattern inWords:(NSArray *)words{ 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern]; 

for (NSString *s in words) { 
    if ([predicate evaluateWithObject:s]) { 
     NSLog(@"there is a match!"); 
     return YES; 
    } 
} 
NSLog(@"sorry, no match found!"); 
return NO; 

}