Perl Regex To Condense Multiple Line Breaks

前端 未结 4 1929
醉话见心
醉话见心 2021-01-14 10:24

I can\'t seem to figure out the right syntax but I want a Perl regular expression to find where there are two or more line breaks in a row and condense them into just 2 line

4条回答
  •  无人及你
    2021-01-14 11:01

    @btilly hit the nail on the head. I did a quick test case:

    in:

    a
    
    b
    
    
    
    
    c
    

    with this code:

    my $line = join '', <>;
    $line =~ s{\n\n+}{\n\n}g;
    print $line;
    

    and it returned the expected result:

    a
    
    b
    
    c
    

    You can get the same result by changing the record separator (and avoiding the regex):

    {
        # change the Record Separator from "\n" to ""
        # treats multiple newlines as just one (perldoc perlvar)
        # local limits the change to the global $/ to this block
        local $/ = "";
        print <>;
    }
    

提交回复
热议问题