-1

我有一个必须使用正则表达式的项目,所以我决定使用RegexKitLite,我下载了它,将RegexKitLite.m添加到“编译源”中,并将RegexKitLite.h 添加到“复制文件”部分。将 libicucore.A.dylib添加到项目库中。将 RegexKitLite.h导入我的班级,并编写代码(仅用于测试):

        NSString *str = @"testing string";
        if ([str isMatchedByRegex:@"[^a-zA-Z0-9]"])
        {
            NSLog(@"Some message here");
        }

之后我有错误消息:

-[__NSCFString isMatchedByRegex:]: unrecognized selector sent to instance 0x1ed45ac0
2013-02-28 19:46:20.732 TextProject[8467:907] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString isMatchedByRegex:]: unrecognized selector sent to instance 0x1ed45ac0'

我错过了什么?请帮我..

4

1 回答 1

1

经过一番挖掘,实际上在 iOS4 之前没有任何 Cocoa API 可以使用正则表达式,因此程序员正在使用像 RegexKitLite 这样确实可以用于 iOS 的外部库。

如果您使用的是 iOS4 或更高版本,则没有任何理由不使用 NSRegularExpression。类参考描述可以在这里找到。

例如,NSRegularExpression您的代码片段将如下所示:

NSString *str = @"testing string";   
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[^a-zA-Z0-9]" options:NSRegularExpressionCaseInsensitive error:nil];
NSTextCheckingResult *match = [regex firstMatchInString:str options:0 range:NSMakeRange(0, [str length])];
NSRange range = [match rangeAtIndex:0];
if (range.location != NSNotFound)
{
    NSString* matchingString = [str substringWithRange:range];
    NSLog(@"%@", matchingString);
}
于 2013-02-28T22:38:04.217 回答