以下代码部分精美结果:
- (void)setRepresentedObject:(id)representedObject { DLOG()
- (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()没有被提及任何人都可以帮忙解决它吗?
答案 0 :(得分: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\n@implementation 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}\n@end"
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()")