How do I remove trailing whitespace using a regular expression?

ellockie picture ellockie · Mar 2, 2012 · Viewed 105k times · Source

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.

Answer

qbert220 picture qbert220 · Mar 2, 2012

Try just removing trailing spaces and tabs:

[ \t]+$