質問

I have a project that must use regular expressions, so I decided to use RegexKitLite, I downloaded it, have added RegexKitLite.m into "Compile Sources", and RegexKitLite.h into "Copy Files" sections. Added libicucore.A.dylib to project Libraries. Imported RegexKitLite.h into my class, and write code (just for test):

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

After that I have error message:

-[__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'

What I have missed? Please help me..

役に立ちましたか?

解決

After some digging there wasn't in fact any Cocoa API to use regex before iOS4 so programmers were using external libraries like RegexKitLite which indeed could be used for iOS.

If you are on iOS4 or later there shouldn't be any reason not to use NSRegularExpression. Class reference description can be found here.

For example with NSRegularExpression your code snippet will look like:

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);
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top