Search code examples
filterwordsnsregularexpressionnsrange

NSRegularExpressions - filtering out words within Xcode


I'm currently teaching myself NSRegularExpressions and how to filter certain things out of RSS feeds. Particularly, the RSS feed is in the format "some text :: (there can be a Re: here for a reply) some text :: some text". I would like to remove that Re: if it exists. I know that there should be a way to do this without creating another NSRegularExpression within the one I currently have. I don't have a grasp on all of the symbols. I was trying to use ?: to uninclude the Re: from capture, but I can't quite figure out how. Would someone mind looking at this for me and giving me a helping hand?

NSRegularExpression *reg = [[NSRegularExpression alloc] initWithPattern:@".* :: ?:Re: (.*) :: .*" options:0 error:nil]; //The () creates a capture group and an array of ranges for reg

    //Loop through every title of the items in channel
    for (RSSItem *i in items) {
        NSString *itemTitle = [i title];
        //find mittts
        //Find matches in the title string. The range argument specifies how much of the title to search; in this case, all of it.
        NSArray *matches = [reg matchesInString:itemTitle options:0 range:NSMakeRange(0, [itemTitle length])];

        //If there was a match...
        if ([matches count] > 0) {
             //Print the location of the match in the string and the string
            NSTextCheckingResult *result = [matches objectAtIndex:0];

            NSRange r = [result range];

            NSLog(@"\nMatch at {%d, %d} for %@!\n", r.location, r.length, itemTitle);


            NSLog(@"Range : %d",[result numberOfRanges]);
            //One capture group, so two ranges, let's verify
            if ([result numberOfRanges] == 2) {
                //Pull out the 2nd range, which will be the capture group
                NSRange r = [result rangeAtIndex:1];

                //Set the title of the item to the string within the capture group
                [i setTitle:[itemTitle substringWithRange:r]];

                NSLog(@"%@", [itemTitle substringWithRange:r]);
            }
        }
    }

Solution

  • Never mind, found it. I needed (?:Re: )? to prevent capturing it.