NSPredicate和简单的正则表达式问题

rjs*_*ing 1 regex cocoa objective-c nspredicate

我遇到简单的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];
Run Code Online (Sandbox Code Playgroud)

在上面的示例isMatch中,始终为false/NO.

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

Mat*_* B. 5

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


Abi*_*ern 5

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

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

NSRange resultRange = [myString rangeWithString:searchString];
BOOL result = resultRange.location != NSNotFound;
Run Code Online (Sandbox Code Playgroud)

改变地,使用谓词

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

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

BOOL result = [testPredicate evaluateWithObject:myString];
Run Code Online (Sandbox Code Playgroud)

我相信文档声明使用谓词是检查子字符串是否存在时的方法.