根据给定的正则表达式模式验证字符串?

时间:2014-10-19 14:54:03

标签: ios objective-c regex

我编写了一个简单的方法来检查给定的数组是否至少有一个字符串,匹配提供的模式...但缺少某些内容并且不确定如何将正结果限制为完整的单词,而不仅仅是第一个适合模式的子字符串。

+ (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;

}

1 个答案:

答案 0 :(得分: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;

}