[英]How to write regular expressions in 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")*/"
它返回: "/*DSLog(@"A string"); NSLog(@"A string2")*/"
。
問題是Objective-C
如何處理正則表達式。 我希望在arrayOfAllMatches
2 個結果,但我只得到一個。 有沒有辦法讓Objective-C
在第一次出現);
停止);
?
問題在於正則表達式。 您正在括號內搜索 .* ,這會導致它包含第一個右括號,繼續執行第二個 NSLog 語句,一直到最后一個右括號。
所以你想做的是這樣的:
NSString *regexStr =@"NSLog\\([^\\)]*\\)[\\s]*\\;";
這告訴它在括號內包含除 ) 字符之外的所有內容。 使用該正則表達式,我得到了兩個匹配項。 (請注意,您在字符串示例中省略了最后一個 ;)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.