How to eliminate ALL line breaks in string?

后端 未结 12 1784
傲寒
傲寒 2021-01-30 10:22

I have a need to get rid of all line breaks that appear in my strings (coming from db). I do it using code below:

value.Replace(\"\\r\\n\", \"\").Replace(\"\\n\"         


        
12条回答
  •  一向
    一向 (楼主)
    2021-01-30 11:10

    Here are some quick solutions with .NET regex:

    • To remove any whitespace from a string: s = Regex.Replace(s, @"\s+", ""); (\s matches any Unicode whitespace chars)
    • To remove all whitespace BUT CR and LF: s = Regex.Replace(s, @"[\s-[\r\n]]+", ""); ([\s-[\r\n]] is a character class containing a subtraction construct, it matches any whitespace but CR and LF)
    • To remove any vertical whitespace, subtract \p{Zs} (any horizontal whitespace but tab) and \t (tab) from \s: s = Regex.Replace(s, @"[\s-[\p{Zs}\t]]+", "");.

    Wrapping the last one into an extension method:

    public static string RemoveLineEndings(this string value)
    {
        return Regex.Replace(value, @"[\s-[\p{Zs}\t]]+", "");
    }
    

    See the regex demo.

提交回复
热议问题