NSString *string = @"A long term stackoverflow.html";
NSString *expression = @"stack(.*).html";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", expression];
BOOL match = [predicate evaluateWithObject:string]
if(match){
NSLog(@"found");
} else {
NSLog(@"not found");
}
我如何搜索表达式是否存在于字符串中。上面的代码正在用于一个单词。但是如果我在字符串中添加更多的单词来进行搜索
答案 0 :(得分:1)
如果您想检查具有正则表达式值的字符串,则应使用NSRegularExpression
而不是NSPredicate
。
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"stack(.*).html" options:0 error:nil];
然后你可以使用这些函数找到匹配...
NSString *string = @"stackoverflow.html";
NSUInteger matchCount = [regex numberOfMatchesInString:string options:0 range:NSMakeRange(0, string.length)];
NSLog(@"Number of matches = %d", matchCount);
注意:我很难创建正则表达式模式,因此我刚刚使用了您的模式和示例。我不知道模式是否会在此字符串中找到匹配项,但如果匹配则可以使用。
答案 1 :(得分:1)
NSPredicate
仅匹配完整的字符串,因此您应该更改模式以覆盖整个字符串:
NSString *expression = @".*stack(.*).html.*";
但是,您的原始模式也会匹配“将我的文件高达html”这样的内容,因此您可能需要阅读正则表达式模式。
答案 2 :(得分:-1)
改善您的问题,但请参阅以下问题的答案
NSString *string = @"This is the main stringsss which needs to be searched for some text the texts can be any big. let us see";
if ([string rangeOfString:@"."].location == NSNotFound) {
NSLog(@"string does not contains");
} else {
NSLog(@"string contains !");
}