【问题标题】:perl - Split string by methods within the stringsperl - 通过字符串中的方法拆分字符串
【发布时间】:2013-08-11 00:28:31
【问题描述】:

我有两个问题:

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

$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:

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

【问题讨论】:

    标签: regex perl


    【解决方案1】:

    并非所有内容都由正则表达式完成,但我认为它更具可读性

    # 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 之前,否则它永远不会被触发。

    【讨论】:

    • 非常感谢,这正是我所需要的。 & 是的,我知道返回之前的表达式 :) 我只希望它用于没有返回的方法,但我可以从这里计算出其余的。再次感谢!
    【解决方案2】:

    你可以使用这个模式:

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

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

    【讨论】:

      猜你喜欢
      • 2016-04-28
      • 1970-01-01
      • 2013-07-07
      • 2012-07-30
      • 1970-01-01
      • 2013-11-08
      • 2014-08-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多