我有两个问题:
首先,如何将以下字符串拆分为通过字符串中的方法拆分的单个字符串?我尝试使用正则表达式,但没有成功。
$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:
并将其添加到字符串中,但无法获取属性本身并将它们添加到第一个 { 之后和最后一个 } 之前
最佳答案
并非所有内容都是由正则表达式完成的,但我认为它更具可读性
# 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
之前,否则永远不会被触发。
关于regex - perl - 按字符串内的方法分割字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18167619/