How can I substitute the nth occurrence of a match in a Perl regex?

前端 未结 5 1784
花落未央
花落未央 2020-12-19 16:24

Following up from an earlier question on extracting the n\'th regex match, I now need to substitute the match, if found.

I thought that I could define the extraction

5条回答
  •  余生分开走
    2020-12-19 17:19

    Or you can do something as this

    use strict;
    use warnings;
    
    my $string = "'How can I','use' .... 'perl','to process this' 'line'";
    
    my $cont =0;
    sub replacen { # auxiliar function: replaces string if incremented counter equals $index
            my ($index,$original,$replacement) = @_;
            $cont++;
            return $cont == $index ? $replacement: $original;
    }
    
    #replace the $index n'th match (1-based counting) from $string by $rep
    sub replace_quoted {
            my ($string, $index,$replacement) = @_;
            $cont = 0; # initialize match counter
            $string =~ s/'(.*?)'/replacen($index,$1,$replacement)/eg;
            return $string;
    }
    
    my $result = replace_quoted ( $string, 3 ,"PERL");
    print "RESULT: $result\n";
    

    A little ugly the "global" $cont variable, that could be polished, but you get the idea.

    Update: a more compact version:

    use strict;
    my $string = "'How can I','use' .... 'perl','to process this' 'line'";
    
    #replace the $index n'th match (1-based counting) from $string by $replacement
    sub replace_quoted {
            my ($string, $index,$replacement) = @_;
            my $cont = 0; # initialize match counter
            $string =~ s/'(.*?)'/$cont++ == $index ? $replacement : $1/eg;
            return $string;
    }
    
    my $result = replace_quoted ( $string, 3 ,"PERL");
    print "RESULT: $result\n";
    

提交回复
热议问题