0

Possible Duplicate:
Regex to strip line comments from C#

I'm completely stuck with this, and i'm not good at making regex.

Basicly i want to match comments in pieces of text, for example this one:

//Comment outside quotations
string text = "//Comment inside quotations..";
//Another comment

I want only the top and bottom comment to match, but not the middle one inside quotations

What i have now for comments is:

//.*$

To match a comment throughout the end of the line.

What i want this to use for is for syntax highlighting in a textBox.

Is this possible to do?

Community
  • 1
  • 1

2 Answers2

1

Try this :

"^(?!\".*\")//.*$"

This will match

//Comment outside quotations

and will not match

string text = "//Comment inside quotations..";

Please make required escaping for c#

Naveed S
  • 5,106
  • 4
  • 34
  • 52
  • @user1944775 Note one thing. This regex works for newline comments only. //CommentX in `string text = "//Comment inside quotations..";//CommentX` will not be matched. – Naveed S Jan 03 '13 at 08:52
0

Try this regex:

([^"]|"[^"]*")*(?<COMMENT>//.*)

Parse each match for the named group "COMMENT" (or whatever you choose to name it). Quick disclaimer that I didn't test it out in C#, I just threw the regex together using an online tool.

Tyson
  • 1,685
  • 15
  • 36