objective-ccocoansstring

Search through NSString using Regular Expression


How might I go about searching/enumerating through an NSString using a regular expression?

A regular expression such as: /(NS|UI)+(\w+)/g.


Solution

  • You need to use NSRegularExpression class.

    Example inspired in the documentation:

    NSString *yourString = @"";
    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression         
        regularExpressionWithPattern:@"(NS|UI)+(\\w+)"
        options:NSRegularExpressionCaseInsensitive
        error:&error];
    [regex enumerateMatchesInString:yourString options:0 range:NSMakeRange(0, [yourString length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){
        // your code to handle matches here
    }];