954,546 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

exclude comments using Regular Expressions

Hi ,

I wanted to know how to write a c# code that reads from a file and counts the number of lines . This count should exclude the comments present

eg :

//this is test
using System;

should not count "//this is test" at all .

Please can someone help me on this one

Thanks
shuchi

shuchimuley
Newbie Poster
4 posts since Dec 2006
Reputation Points: 10
Solved Threads: 0
 

you could use the line.BeginsWith or line.StartsWith (forgot which one it is), and pass in "//". If it returns true, then don't count the line and go to the next line.

mariocatch
Junior Poster
103 posts since Apr 2007
Reputation Points: 11
Solved Threads: 17
 
iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439
 

i gotta use regex.match(regularexpression) . I am using a streamreader to read the whole file and then the contents of the file are match with the pattern of the regular expression . and this regular expression needs to count all the lines of code excluding watever is written in comments .

eg

//test1
//test2
/* test3 */
using System;
using System.Collections.Generic; /* test4 */
using System.Text;
using System.Collections;
using System.IO;
using System.Text.RegularExpressions;
namespace Regular_Test
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Good");
}
}
}

this shud remove all the comments .. ie shud count all the line of code except comments (/*..*/) , (//) wherever they appear .

shuchimuley
Newbie Poster
4 posts since Dec 2006
Reputation Points: 10
Solved Threads: 0
 

Well the idea would be to write a very trivial regex expression and then apply it on a code snippet. Then you would add to that regex expression gradually getting more complex.

iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439
 

sounds like homework. Show us what you have tried and then we can help

campkev
Posting Pro in Training
484 posts since Jul 2005
Reputation Points: 14
Solved Threads: 19
 
(//.*\n|/\*(.|\n)*?\*/)


untested...

iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439
 

well well well ,
i made a C# program that now reads a file and excluding the comments out.. that worked .. thanks to all . :)

shuchimuley
Newbie Poster
4 posts since Dec 2006
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You