Search code examples
regexwhitespacetrailing

How do I remove trailing whitespace using a regular expression?


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

I tried:

\s+$

and:

([^\n]*)\s+\r\n

But they all removed empty lines too. I guess \s matches end-of-line characters too.


UPDATE (2016):

Nowadays I automate such code cleaning by using Sublime's TrailingSpaces package, with custom/user setting:

"trailing_spaces_trim_on_save": true

It highlights trailing white spaces and automatically trims them on save.


Solution

  • Try just removing trailing spaces and tabs:

    [ \t]+$