2017-07-06 76 views
0

繼代碼段重建串精美的結果: - (void)setRepresentedObject:(id)representedObject { DLOG()NSRegularExpression:stringByReplacingMatchesInString不能與多行

- (void) putLogInFunctionCalls{ 

NSString *string = @"- (void)setRepresentedObject:(id)representedObject {"; 
NSError *error = nil; 
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^-[^{]+\{" options:NSRegularExpressionCaseInsensitive error:&error]; 

NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:[NSString stringWithFormat:@"%@ DLOG()", string]]; 

NSLog(@"%@", modifiedString); 

}

但不是把只是一個線路輸入的變量字符串,如果我嘗試閱讀代碼文件說,ViewController.m文件,其中包含以下代碼,並將其放在該變量:它不起作用。

// 
// ViewController.m 
// ForCommonCoding 
// 
// Created by A Programmer on 7/6/17. 
// Copyright ? 2017 A Programmer. All rights reserved. 
// 

#import "ViewController.h" 


@implementation ViewController 

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    // Do any additional setup after loading the view. 
} 
- (void)setRepresentedObject:(id)representedObject { 
     [super setRepresentedObject:representedObject]; 

    // Update the view, if already loaded. 
} 

- (void)sampleFunction { 
    NSLog(@"This is sampleFunction"); 
} 
@end 

NSLog顯示與輸入相同。 DLog()沒有appendded任何人都可以幫助解決它?

回答

0

這應該工作,你希望:

NSError *error = nil; 
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^(-[^{]+\{)" options:NSRegularExpressionAnchorsMatchLines error:&error]; 
NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:@"$1 DLOG()"]; 
NSLog(@"%@", modifiedString); 

的三個問題與您的代碼:

  • NSRegularExpressionAnchorsMatchLines失蹤了,但你匹配線開始^

  • 正則表達式中缺少匹配組,允許您使用替換後的匹配結果:()

  • 更換模板字符串使用整個string,而不是第一場比賽$1

工作遊樂場代碼:

let line = "- (void)setRepresentedObject:(id)representedObject {" 
let file = "#import \"ViewController.h\"\n\n\[email protected] ViewController\n\n- (void)viewDidLoad {\n [super viewDidLoad];\n\n // Do any additional setup after loading the view.\n}\n- (void)setRepresentedObject:(id)representedObject {\n   [super setRepresentedObject:representedObject];\n\n  // Update the view, if already loaded.\n}\n\n- (void)sampleFunction {\n NSLog(@\"This is sampleFunction\");\n}\[email protected]" 
let regex = try! NSRegularExpression(pattern: "^(-[^{]+\\{)", options: [.anchorsMatchLines]) 
regex.stringByReplacingMatches(in: line, options: [], range: NSMakeRange(0, line.characters.count), withTemplate: "$1 DLOG()") 
regex.stringByReplacingMatches(in: file, options: [], range: NSMakeRange(0, file.characters.count), withTemplate: "$1 DLOG()")