How to perform search-and-replace within given $start-$end ranges?

后端 未结 4 770
星月不相逢
星月不相逢 2021-01-15 09:54

Say, a text file have many $start-$end pairs, and within each pair there are some text. I want Perl to find-and-replace all $patterns with the

4条回答
  •  北海茫月
    2021-01-15 10:22

    I find things like this are most simply done using the @- and @+ built-in arrays in conjunction with substr as an lvalue

    $-[1] contains the offset within the string where the first capture began, while $+[1] contains the offset where it ended. Hence $+[1]-$-[1] is the length of the captured section

    This program finds all occurrences of /START(.+?)END/ and edits the captured section -- the region between START and END -- by applying a regex substitution to that substring

    You may need to chnage this slightly depending on the real-world data that you're working with

    use strict;
    use warnings 'all';
    use feature 'say';
    
    my $str = 'xx START xx bingo xx bingo xx END xx bingo xx START xx bingo xx END bingo';
    my ($start, $end, $pattern, $replacement) = qw/ START END bingo okyes /;
    
    while ( $str =~ /\b$start\b(.+?)\b$end\b/gs ) {
         substr($str, $-[1], $+[1]-$-[1]) =~ s/$pattern/$replacement/g;
    }
    
    say $str;
    

    output

    xx START xx okyes xx okyes xx END xx bingo xx START xx okyes xx END bingo
    

提交回复
热议问题