Objective C - 具有特定子字符串的 NSRegularExpression

Objective C - NSRegularExpression with specific substring

我有一个 NSString,我正在检查是否有 NSLog,然后我将其注释掉。 我正在使用 NSRegularExpression 然后遍历结果。 代码:

-(NSString*)commentNSLogFromLine:(NSString*)lineStr {

    NSString  *regexStr =@"NSLog\(.*\)[\s]*\;";

    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:NSRegularExpressionCaseInsensitive error:nil];

    NSArray *arrayOfAllMatches = [regex matchesInString:lineStr options:0 range:NSMakeRange(0, [lineStr length])];

    NSMutableString *mutStr = [[NSMutableString alloc]initWithString:lineStr];

    for (NSTextCheckingResult *textCheck in arrayOfAllMatches) {

        if (textCheck) {
            NSRange matchRange = [textCheck range];
            NSString *strToReplace = [lineStr substringWithRange:matchRange];
            NSString *commentedStr = [NSString stringWithFormat:@"/*%@*/",[lineStr substringWithRange:matchRange]];
            [mutStr replaceOccurrencesOfString:strToReplace withString:commentedStr options:NSCaseInsensitiveSearch range:matchRange];

            NSRange rOriginal = [mutStr rangeOfString:@"NSLog("];
            if (NSNotFound != rOriginal.location) {
                [mutStr replaceOccurrencesOfString:@"NSLog(" withString:@"DSLog(" options:NSCaseInsensitiveSearch range:rOriginal];
            }
        }
    }

    return [NSString stringWithString:mutStr];

}

问题出在测试用例上:

NSString *str = @"NSLog(@"A string"); NSLog(@"A string2")"

而不是返回 "/*DSLog(@"A string");*/ /*DSLog(@"A string2")*/" 它 returns: "/*DSLog(@"A string"); NSLog(@"A string2")*/".

问题在于 Objective-C 如何处理正则表达式。我希望 arrayOfAllMatches 中有 2 个结果,但我只得到一个。有什么方法可以让 Objective-C); 第一次出现时停止?

问题出在正则表达式上。您在括号内搜索 .*,这导致它包含第一个右括号,继续执行第二个 NSLog 语句,一直到最后一个右括号。

所以你想做的是这样的:

NSString  *regexStr =@"NSLog\([^\)]*\)[\s]*\;";

这告诉它包括括号内的所有内容,除了 ) 字符。使用该正则表达式,我得到了两个匹配项。 (请注意,您在字符串示例中省略了最后一个 ;)。