How do I remove trailing whitespace using a regular expression?

后端 未结 10 2179
无人及你
无人及你 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:16

    If using Visual Studio 2012 and later (which uses .NET regular expressions), you can remove trailing whitespace without removing blank lines by using the following regex

    Replace (?([^\r\n])\s)+(\r?\n)

    With $1


    Some explanation

    The reason you need the rather complicated expression is that the character class \s matches spaces, tabs and newline characters, so \s+ will match a group of lines containing only whitespace. It doesn't help adding a $ termination to this regex, because this will still match a group of lines containing only whitespace and newline characters.

    You may also want to know (as I did) exactly what the (?([^\r\n])\s) expression means. This is an Alternation Construct, which effectively means match to the whitespace character class if it is not a carriage return or linefeed.

    Alternation constructs normally have a true and false part,

    (?( expression ) yes | no )

    but in this case the false part is not specified.

提交回复
热议问题