How do I remove trailing whitespace using a regular expression?

后端 未结 10 2182
无人及你
无人及你 2021-01-30 04:00

I want to remove trailing white spaces and tabs from my code without removing empty lines.

I tried:

\\s+$

and:

([^\\n]         


        
10条回答
  •  悲&欢浪女
    2021-01-30 04:19

    The platform is not specified, but in C# (.NET) it would be:

    Regular expression (presumes the multiline option - the example below uses it):

        [ \t]+(\r?$)
    

    Replacement:

        $1
    

    For an explanation of "\r?$", see Regular Expression Options, Multiline Mode (MSDN).

    Code example

    This will remove all trailing spaces and all trailing TABs in all lines:

    string inputText = "     Hello, World!  \r\n" +
                       "  Some other line\r\n" +
                       "     The last line  ";
    string cleanedUpText = Regex.Replace(inputText,
                                         @"[ \t]+(\r?$)", @"$1",
                                         RegexOptions.Multiline);
    

提交回复
热议问题