BlackM BlackM - 1 year ago 124
Objective-C Question

Objective C - NSRegularExpression with specific substring

I have an

which I am checking if there is an
and then I comment it out.
I am using
and then looping through result.
The code:

-(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];


The problem is with the test case:

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

Instead of returning
"/*DSLog(@"A string");*/ /*DSLog(@"A string2")*/"
it returns:
"/*DSLog(@"A string"); NSLog(@"A string2")*/"

The issue is how the
handles the regular expression. I would expected 2 results in
but instead that I am getting only one. Is there any way to ask
to stop on the first occurrence of

Answer Source

The problem is with the regular expression. You are searching for .* inside the parentheses, which causes it to include the first close parenthesis, continue through the second NSLog statement, and go all the way to the final close parentheses.

So what you want to do is something like this:

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

That tells it to include everything inside the parenthesis except for the ) character. Using that regex, I get two matches. (note that you omitted the final ; in your string sample).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download