Search code examples
.netregexcommentsreplacetextpad

Delete all comments in C# code using TextPad 'Find And Replace' using Regular Expression


I want to get rid of all comments in a C# file using a TextPad regular expression, using the Find And Replace feature. I don't need one regular expression to do this. I don't mind making multiple passes.

Scenarios:

If C# source code line contains code, remove the white spaces and comments after the code. If the C# source code line(s) contains no actual code, remove the entire line(s).

 x = y;  /* comment on single line */

 x = y;  // comment on single line

 x = y;  /* comment on multiple lines
            comment on multiple lines */

Are there any I'm missing?


Solution

  • I love TextPad! First of all, make sure you are using POSIX syntax (go to Configure > Preferences > Editor and enable "use POSIX regular expression syntax").

    Indeed, you will need several passes:

    1. Replace \/\*+.*\*+\/ for nothing.
    2. Replace \/\/+.*$ for nothing.
    3. Replace \/\*+.*$ for nothing.
    4. Replace ^.*\*+\/\b*$ for nothing.

    This will also remove something like:

    /*** comment on single line ***/
    

    or

    //// comment on single line
    

    It may be a good idea to record a macro so you can remove comments with a single click. There's are macros for commenting and uncommenting Javascript code that should work with C# code as well: http://www.textpad.com/add-ons/macros.html