regex - perl - 按字符串内的方法分割字符串

标签 regex perl

我有两个问题:

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

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

相关文章:

perl - 嵌套 while 循环比较两个文件,外部循环在一次迭代后停止,需要比较文件的每一行

regex - 为什么 `$str1 =~ "foo "` recognized as ` $str1 =~ m/foo/`(而不是语法错误)?

html - 如何使用 Perl 有效地提取 HTML 内容?

regex - Amazon Cloudwatch Logs Insights 使用正则表达式进行解析

sql - Oracle SQL regexp_replace 在 OR 组处停止

regex - Vim 正则表达式在行首匹配方括号失败

javascript - 正则表达式元音到 1337 个数字

ios - 为什么此 Regex 代码不适用于 P.O.箱子串?

regex - 如何使用 split 捕获正则表达式交替的匹配组?

multithreading - 线程占用大量CPU