[英]Validating strings against given regex pattern?
我写了一种简单的方法来检查给定的数组是否至少有一个字符串,该字符串是否匹配提供的模式...但是缺少某些内容,并且不确定如何将肯定结果仅限制为完整的单词,而不仅限于适合模式的第一个子字符串。
+ (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;
}
愚蠢的我,有一种更简单的方法:)基于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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.