Removing all whitespace lines from a multi-line string efficiently

前端 未结 19 2117
名媛妹妹
名媛妹妹 2020-12-29 04:25

In C# what\'s the best way to remove blank lines i.e., lines that contain only whitespace from a string? I\'m happy to use a Regex if that\'s the best solution.

EDIT

19条回答
  •  暖寄归人
    2020-12-29 04:38

    In response to Will's bounty here is a Perl sub that gives correct response to the test case:

    sub StripWhitespace {
        my $str = shift;
        print "'",$str,"'\n";
        $str =~ s/(?:\R+\s+(\R)+)|(?:()\R+)$/$1/g;
        print "'",$str,"'\n";
        return $str;
    }
    StripWhitespace("test\r\n \r\nthis\r\n\r\n");
    

    output:

    'test
    
    this
    
    '
    'test
    this'
    

    In order to not use \R, replace it with [\r\n] and inverse the alternative. This one produces the same result:

    $str =~ s/(?:(\S)[\r\n]+)|(?:[\r\n]+\s+([\r\n])+)/$1/g;
    

    There're no needs for special configuration neither multi line support. Nevertheless you can add s flag if it's mandatory.

    $str =~ s/(?:(\S)[\r\n]+)|(?:[\r\n]+\s+([\r\n])+)/$1/sg;
    

提交回复
热议问题