我有两个问题:
首先,如何将以下字符串拆分为由字符串中的方法拆分的单个字符串?我尝试使用正则表达式,但没有成功。
$objc = "- (void)method {
NSLog(@"method");
if (1 == 1) {
//blah blah blah
}
}
- (id)otherMethodWithProperty:(NSString *)property {
NSLog(@"otherMethodWithProperty:");
return property;
}
-(id) methodWithMoreProperties: (id)property Property2:(UIView *)property2 Property3:(NSString *)property3 {
id view = property;
if (view) {
NSLog(@"%@", view);
}
return view;
}"
第二个问题是在分成单个字符串后,是否可以获取每个属性并将其添加到相应的字符串中?例如:
我拿着字符串:
"-(id) methodWithMoreProperties: (id)property Property2:(UIView *)property2 Property3:(NSString *)property3 {
id view = property;
if (view) {
NSLog(@"%@", view);
}
return view;
}"
获取属性“property,property2,property3”并在第一个“{”之后和最后一个“}”之前的字符串中添加它们:
"-(id) methodWithMoreProperties: (id)property Property2:(UIView *)property2 Property3:(NSString *)property3 {
NSLog(@"%@\n%@\n%@", property, property2, property3);
id view = property;
if (view) {
NSLog(@"%@", view);
}
return view;
NSLog(@"FINISH: %@\n%@\n%@", property, property2, property3);
}"
我一直在谷歌搜索和测试代码几个小时,我只使用正则表达式来管理方法名称
- (id)methodWithMoreProperties:
并将其添加到字符串中,但无法自己抓取属性并在第一个{和最后一个}之后添加它们
答案 0 :(得分:3)
并非所有内容都由正则表达式完成,但我认为它更具可读性
# split string into methods
my @methods = split /^-/m, $objc;
foreach my $method_content (@methods) {
my $method_declaration = (split /{/, $method_content, 2)[0];
my ($method_name, @properties) = $method_declaration =~ /\)\s*(\w+)/g;
if (@properties) {
my $sprintf_format = join '\n', ('%@') x @properties;
my $sprintf_values = join ', ', @properties;
my $begin_message = sprintf 'NSLog(@"%s", %s);', $sprintf_format, $sprintf_values;
my $end_message = sprintf 'NSLog(@"FINISH: %s", %s);', $sprintf_format, $sprintf_values;
$method_content =~ s/{/{\n $begin_message/;
$method_content =~ s/}\s*$/ $end_message\n}\n\n/;
}
print "-$method_content";
}
但$end_message
最好放在方法的return
之前,否则永远不会被触发。
答案 1 :(得分:1)
您可以使用此模式:
my @matches = $objc =~ /(-\s*+\([^)]++\)(?>\s*+\w++(?>:\s*+\([^)]++\)\s*+\w++)?+)*+\s*+({(?>[^{}]++|(?-1))*+}))/g;
(您只需根据需要自定义捕获组)