1

我在使用简单的 NSPredicates 和正则表达式时遇到问题:

NSString *mystring = @"file://questions/123456789/desc-text-here";
NSString *regex = @"file://questions+";

NSPredicate *regextest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
BOOL isMatch = [regextest evaluateWithObject:mystring];

在上面的例子isMatch中总是假/否。

我错过了什么?我似乎找不到匹配的正则表达式file://questions

4

2 回答 2

5

NSPredicates 似乎尝试匹配整个字符串,而不仅仅是一个子字符串。您的尾随+只是意味着匹配一个或多个 's' 字符。您需要允许匹配任何尾随字符。这有效:regex = @"file://questions.*"

于 2009-10-17T17:34:55.313 回答
5

如果您只是想测试字符串是否存在:试试这个

NSString *myString = @"file://questions/123456789/desc-text-here";
NSString *searchString = @"file://questions";

NSRange resultRange = [myString rangeWithString:searchString];
BOOL result = resultRange.location != NSNotFound;

或者,使用谓词

NSString *myString = @"file://questions/123456789/desc-text-here";
NSString *searchString = @"file://questions";

NSPredicate *testPredicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH %@", searchString];

BOOL result = [testPredicate evaluateWithObject:myString];

我相信文档指出,在检查子字符串是否存在时,使用谓词是要走的路。

于 2009-10-17T17:37:23.407 回答