Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
perl模式逐个匹配并处理它_Perl_Pattern Matching_Substitution - Fatal编程技术网

perl模式逐个匹配并处理它

perl模式逐个匹配并处理它,perl,pattern-matching,substitution,Perl,Pattern Matching,Substitution,我有一根绳子 [something]text1[/something] blah blah [something]text2[/something] 我需要编写一个Perl脚本来读取[something]标记中的内容,将其处理为“text-x”,并将其与[otherthing]标记一起放回。所以上面的字符串应该是 [otherthing]text-1[/otherthing] blah blah [otherthing]text-2[/otherthing] 将“textx”处理为“text

我有一根绳子

[something]text1[/something] blah blah [something]text2[/something]
我需要编写一个Perl脚本来读取
[something]
标记中的内容,将其处理为“text-x”,并将其与
[otherthing]
标记一起放回。所以上面的字符串应该是

[otherthing]text-1[/otherthing] blah blah [otherthing]text-2[/otherthing]
将“textx”处理为“text-x”不是一步过程

这就是我到目前为止的解决方案:

m/[something](?<text>.*)[/something]/
m/[something](?*)[/something]/
这将得到介于两者之间的字符串,我可以将其处理为“text-x”,但如何将其放回与
[otherthing]text-x[/otherthing]
相同的位置

  • 在这种情况下,如何使用s//
  • 怎么把整根绳子一根一根地接起来

  • 在这种特殊情况下,您可以通过在
    “[某物]”
    上拆分字符串,然后处理每个片段的开头(第一个片段除外),然后在完成后将片段重新连接在一起来完成您试图完成的任务


    我不知道在Perl中是否有一种在字符串中迭代正则表达式匹配的通用方法。我希望其他人能回答这个问题并对我进行教育。

    在将结果用作替换之前,您可以使用
    /e
    开关打开
    s//
    来评估右手侧,并使用
    /g
    标记对每一场比赛执行此操作

    下面是一个简单的例子:

    use 5.12.0;
    
    my $str = ">1<  >2<  >34<";
    
    $str =~ s/>(\d+)</">>".process("$1")."<<"/eg;
    
    say $str;
    
    sub process {
        return "x" x $_[0];
    }
    
    使用5.12.0;
    
    my$str=“>1<>2<>34>”。process(“$1”)。“这应该很接近。它使用/e修饰符允许您在正则表达式的替换端进行处理,因此它调用fix_textx函数,您可以在其中执行多个步骤

    迭代匹配的正常方法是使用/g修饰符

    #!/usr/bin/perl
    use strict;
    use warnings;
    
    my $string = '[something]text1[/something] blah blah [something]text2[/something]';
    
    $string =~ s{\[something\](text[^[]*)\[\/something\]}
                {'[otherthing]' . fix_textx($1) . '[/otherthing]'}ge;
    
    print $string;
    
    sub fix_textx {
        my ($testx) = @_;
        $testx =~ s/text\K(.*)/-$1/;
        return $testx;
    }
    

    编辑:修复了方括号。感谢@tadmc

    ,regex将无法工作,因为
    [
    ]
    /
    是未替换的元字符。您的char类中的方括号朝向错误的方向,应该是(text[^[]*)。