0

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?

JustBeingHelpful
  • 18,332
  • 38
  • 160
  • 245

2 Answers2

1

Using the regex pattern: (/([^]|[\r\n]|(+([^/]|[\r\n])))*+/)|(//.)

see more https://code.msdn.microsoft.com/How-to-find-code-comments-9d1f7a29/

frank tan
  • 131
  • 1
  • 4
1

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

Diego
  • 18,035
  • 5
  • 62
  • 66
  • thanks dude!! Me too! I used to write these regular expressions all the time back in college, but I lost my arsenal (or misplaced it in my stack of CDs). I never heard about the POSIX syntax before. – JustBeingHelpful Mar 24 '12 at 17:35
  • I just checked and they seem to work without enabling POSIX syntax. – Diego Mar 24 '12 at 18:00
  • 1
    In these expressions, remove all the `+`s, they are completely useless. And you need a `?` after the first `.*`, and you can remove all the `$` (if `.` doesn't match new lines, if it does you need to ungreedy all those quantifiers instead). And `\b*`? What do you mean with that? It makes no sense here. – Qtax Mar 24 '12 at 19:49