2

我有两个问题:

首先,如何将以下字符串拆分为由字符串中的方法拆分的单个字符串?我尝试使用正则表达式,但不成功。

$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)方法WithMoreProperties:

并将其添加到字符串中,但无法自己获取属性并将它们添加到第一个 { 和最后一个 } 之前

4

2 回答 2

3

not all was done by regex, but I think it's more readable

# 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";
}

but the $end_message should be better put before the methods's return or it'll never be triggered.

于 2013-08-11T07:31:23.300 回答
1

您可以使用此模式:

my @matches = $objc =~ /(-\s*+\([^)]++\)(?>\s*+\w++(?>:\s*+\([^)]++\)\s*+\w++)?+)*+\s*+({(?>[^{}]++|(?-1))*+}))/g;

(您只需要根据需要对捕获组进行服装化)

于 2013-08-11T02:13:49.107 回答