Home > C# > Removing trailing spaces in Visual Studio

Removing trailing spaces in Visual Studio

November 30th, 2010 Leave a comment Go to comments

Trailing spaces or tabs is something I dislike. Using the combination CTRL+R, CTRL+W you can show the whitespace distribution in VS. But screening the lines one by one is a tedious job. That’s why we are going to use regular expressions. Regular expressions in VS are a bit of an odd duck as the syntax is not nice and Perly.

You can read more about regular expressions in Visual Studio here.

Putting this together we get the following:

Find what: ^{.@}:b+$
Replace with: \1

This will seach those nasty trailing whitespaces and remove them.
{.@} -> Match everything, non-greedy. This is our capturing group.
:b+$ -> Match one or more spaces or tabs before the end of the line.

You can add the following macro to Visual Studio (and bind some keystroke):

Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports System.Diagnostics
Public Module Famvdploeg
    'Remove trailing whitespace from document
    Sub RemoveTrailingWhitespace()
        DTE.Find.FindReplace(vsFindAction.vsFindActionReplaceAll, "( |\t)+$", vsFindOptions.vsFindOptionsRegularExpression, String.Empty, vsFindTarget.vsFindTargetCurrentDocument, , , )
    End Sub
End Module
  1. Jay
    January 28th, 2011 at 17:17 | #1

    Simpler would be to replace :b+$ with nothing.

  2. Wytze
    February 1st, 2011 at 14:40 | #2


    Does not work for me. Also that would probably match every line instead of just the lines with trailing spaces.

  3. May 13th, 2011 at 05:30 | #3

    My question is related to wordpress posting. I cant find any contact address of the author, thats why I am posting comment for this post as my question.
    I have created a wordpress blog tuvian.wordpress.com and I am started post from recent days. I want to know that how we can post codes (C#,html..) in the blog with apprpriate style. What I was done is just copy paste the codes from Visual Studio and lost all styles when I published the blog.
    I am using same style and css that you using here, I would like to know how you posted above comments inside the gray box.

    thanks and regards

  4. May 13th, 2011 at 14:15 | #4

    It’s a plugin for wordpress called wp-syntax.

  1. No trackbacks yet.

Time limit is exhausted. Please reload CAPTCHA.