Perl Regex To Condense Multiple Line Breaks

前端 未结 4 1923
醉话见心
醉话见心 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

    This does it:

    #!/usr/bin/env perl
    use strict;
    use warnings;
    my $string;
    {
       local $/=undef;
       $string =;
    } 
    print "Before:\n$string\n============";
    
    $string=~s/\n{2,}/\n\n/g;
    print "After:\n$string\n\nBye Bye!";
    
    __DATA__
    Line 1
    Line 2
    
    
    
    
    
    
    Line 9
    Line 10
    
    Line 12
    
    
    
    Line 16
    
    
    Line 19
    

    Output:

    Before:
    Line 1
    Line 2
    
    
    
    
    
    
    Line 9
    Line 10
    
    Line 12
    
    
    
    Line 16
    
    
    Line 19
    ============After:
    Line 1
    Line 2
    
    Line 9
    Line 10
    
    Line 12
    
    Line 16
    
    Line 19
    

    Perl also supports the \R character class for platform independence. See this SO link. Your regex would then be s/\R{2,}/\n\n/g;

提交回复
热议问题