0

I have a lot of code and would like to find and replace some text in it. I want to replace all matches, but excluding those that are in comments. Suppose I want to find and replace string "text" in my code. Example:

Console.WriteLine("text"); // must be replaced 
// some text    /* does not need to be replaced because this string begins from  "//"  */ 

Unfortunately, I don't know how to do it with regular expressions. Could someone help me?

Alan Moore
  • 68,531
  • 11
  • 88
  • 149
Itsme
  • 11
  • 1
  • what would the output in second line? – vks Oct 22 '14 at 08:43
  • the second line does not be found. Regex i wanna get hasn't to match "text" in second line – Itsme Oct 22 '14 at 08:48
  • Which tool are you using? – nhahtdh Oct 22 '14 at 08:55
  • possible duplicate of [Regex for comments in strings, strings in comments, etc](http://stackoverflow.com/questions/25402109/regex-for-comments-in-strings-strings-in-comments-etc) – asontu Oct 22 '14 at 09:26
  • @funkwurm: Not dup. This searching for some text outside comment, not extracting the parts. Your post is useful if it is possible to supply a replacement function, though. – nhahtdh Oct 22 '14 at 09:37
  • So the thing is that you wanna search for both the comment and the text, and only handling the capture-group that contains the text. That way text inside the comment gets captured in a capture-group that you leave alone. This is more thoroughly explained **[here](http://stackoverflow.com/questions/23589174/regex-pattern-to-match-excluding-when-except-between/23589204#23589204)**. But if you expect line-comment delimiters inside strings, you should _also_ capture those to prevent them from getting captured as a comment, etc. – asontu Oct 22 '14 at 11:12

2 Answers2

0

Going strictly by the requirement "find text unless surrounded by // and \n", this would be the regex to use and only handle capture group 1. But note (like I said in the comment) that comment-delimiters inside string aren't accounted for, as the 3rd line in the debuggex demo shows. nhahtdh is correct in saying that a replace callback function would be the way to go here, you can then capture any string and further investigate it in the callback.

\/\/[^\n]*(?:\n|$)|(text)

Regular expression visualization

Debuggex Demo

asontu
  • 4,264
  • 1
  • 17
  • 25
-1
^[^\/]+(\/\/.*)\n

I think this should suit your needs

Vajura
  • 1,054
  • 7
  • 15