NSRegularExpressions - 过滤掉Xcode中的单词

时间:2012-10-17 18:20:09

标签: filter words nsregularexpression nsrange

我目前正在教自己NSRegularExpressions以及如何过滤RSS feed中的某些内容。特别是,RSS提要的格式为“some text ::(可以有Re:这里有回复)一些文本:: some text”。我想删除Re:如果它存在。我知道应该有一种方法可以做到这一点,而不在我现有的NSRegularExpression中创建另一个NSRegularExpression。我没有掌握所有的符号。我试图使用?:不包括Re:从捕获,但我无法弄清楚如何。有人会介意为我看这个并给我一个帮助吗?

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]);
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

没关系,发现它。我需要(?:Re :)?防止捕获它。