0

Is it possible to use a Regular Expression to extract only comments from a C# file?

If so how would you do that?

dash
  • 89,546
  • 4
  • 51
  • 71
user1522673
  • 113
  • 1
  • 6
  • For /*...*/ style comments, you could just invert the solution from this question: http://stackoverflow.com/questions/6138296/regular-expression-needed-to-remove-c-c-comments - remember, the RegEx you use to replace comments can also be used to find them. – dash Jul 13 '12 at 10:41

2 Answers2

2

Refer this: -> Finding Comments in Source Code Using Regular Expressions

after reading the article, your final RegEx would be.

(/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/)|(//.*)

FOR C#

^/[/|*](.+)$ (for single line comment )
(^\/\/.*?$|\/\*.*?\*\/) (for multilne comments)
patel.milanb
  • 5,822
  • 15
  • 56
  • 92
  • 2
    This is nice, but it would fail to find "single-line" comments that don't start at the beginning of the line. This is probably better accomplished with some type of parser/filter rather than a regular expression. – Brian Warshaw Jul 13 '12 at 11:02
0

This Regex finds all the comments in a C# file.

(((?<=//).+(?=\n))|((?<=/*)[^(\*/)]+(?=\*/)))+
Max
  • 315
  • 1
  • 13