如何替换字符串中多次出现的一对字符?

How can I replace one pair of character with multiple occurrence in a string?

原字符串是:这是一个带(名词)(动词)(副词)的句子。

原句出现3次()。我需要最后一个完好无损,但用 @"""

替换其余部分

必填字符串:这是一个带(副词)的句子。

我可以用 NSRange 做到这一点,但我正在寻找 NSRegularExpression 模式。 还有哪个更有效,一个是 NSRange 还是 NSRegularExpression。

代码

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\(.*?\)" options:NSRegularExpressionCaseInsensitive error:NULL];
NSString *newString = [regex stringByReplacingMatchesInString:modify options:0 range:NSMakeRange(0, [modify length]) withTemplate:@""];

输出::这是一个带有

的句子

可以自己获取匹配范围,手动替换,忽略最后一个。

NSMutableString* newString = [modify mutableCopy];
NSArray<NSTextCheckingResult*>* matches = [regex matchesInString:newString options:0 range:NSMakeRange(0, newString.length)];
if (matches.count >= 2)
{
    // Enumerate backwards so that each replacement doesn't invalidate the other ranges
    for (NSInteger i = matches.count - 2; i >= 0; i--)
    {
        NSTextCheckingResult* result = matches[i];
        [newString replaceCharactersInRange:result.range withString:@""];
    }
}