Removing all whitespace lines from a multi-line string efficiently

前端 未结 19 1981
名媛妹妹
名媛妹妹 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:34

    not good. I would use this one using JSON.net:

    var o = JsonConvert.DeserializeObject(prettyJson);
    new minifiedJson = JsonConvert.SerializeObject(o, Formatting.None);
    
    0 讨论(0)
  • 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;
    
    0 讨论(0)
  • 2020-12-29 04:38
    char[] delimiters = new char[] { '\r', '\n' };
    string[] lines = value.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
    string result = string.Join(Environment.NewLine, lines)
    
    0 讨论(0)
  • 2020-12-29 04:41

    if its only White spaces why don't you use the C# string method

        string yourstring = "A O P V 1.5";
        yourstring.Replace("  ", string.empty);
    

    result will be "AOPV1.5"

    0 讨论(0)
  • 2020-12-29 04:41

    String Extension

    public static string UnPrettyJson(this string s)
    {
        try
        {
            // var jsonObj = Json.Decode(s);
            // var sObject = Json.Encode(value);   dont work well with array of strings c:['a','b','c']
    
            object jsonObj = JsonConvert.DeserializeObject(s);
            return JsonConvert.SerializeObject(jsonObj, Formatting.None);
        }
        catch (Exception e)
        {
            throw new Exception(
                s + " Is Not a valid JSON ! (please validate it in http://www.jsoneditoronline.org )", e);
        }
    }
    
    0 讨论(0)
  • 2020-12-29 04:44

    Here is something simple if working against each individual line...

    (^\s+|\s+|^)$
    
    0 讨论(0)
提交回复
热议问题