Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 569
ellockie Avatar asked Mar 02 '12 11:03

ellockie


People also ask

How do I get rid of whitespace trailing?

Type M-x delete-trailing-whitespace to delete all trailing whitespace. This command deletes all extra spaces at the end of each line in the buffer, and all empty lines at the end of the buffer; to ignore the latter, change the variable delete-trailing-lines to nil .

How do I trim a whitespace in regex?

Trimming WhitespaceSearch for [ \t]+$ to trim trailing whitespace. Do both by combining the regular expressions into ^[ \t]+|[ \t]+$. Instead of [ \t] which matches a space or a tab, you can expand the character class into [ \t\r\n] if you also want to strip line breaks. Or you can use the shorthand \s instead.

Which regex would you use to remove all whitespace from string?

Use the String. replace() method to remove all whitespace from a string, e.g. str. replace(/\s/g, '') . The replace() method will remove all whitespace characters by replacing them with an empty string.

What function is used to remove trailing spaces from the string?

strip() Python String strip() function will remove leading and trailing whitespaces. If you want to remove only leading or trailing spaces, use lstrip() or rstrip() function instead.


2 Answers

Try just removing trailing spaces and tabs:

[ \t]+$ 
like image 166
qbert220 Avatar answered Sep 27 '22 19:09

qbert220


To remove trailing whitespace while also preserving whitespace-only lines, you want the regex to only remove trailing whitespace after non-whitespace characters. So you need to first check for a non-whitespace character. This means that the non-whitespace character will be included in the match, so you need to include it in the replacement.

Regex: ([^ \t\r\n])[ \t]+$

Replacement: \1 or $1, depending on the IDE

like image 36
KOVIKO Avatar answered Sep 27 '22 19:09

KOVIKO