开发者

How to regexp replace something not in comment?

开发者 https://www.devze.com 2023-03-15 14:41 出处:网络
How using regexp replace something in code that is not a comment? ..PATTERN.. PATTERN // .. PATTERN ..

How using regexp replace something in code that is not a comment?

..PATTERN.. PATTERN // .. PATTERN ..

to

..ANOTHER.. ANOTHER // .. PATTERN ..

Comments can be // or /* */

Regexp to find comment开发者_如何学编程s is:

/\*(.|[\r\n])*?\*/|(//.*)


You can easily do this for single line comments by using a negative lookbehind (but still prone to problem of literal string of the form "....//....."):

string target = "replace // don't replace";
var output = Regex.Replace(target, "(?<!//.*)replace", "new string");
Console.WriteLine(output); //  new string // don't replace

Maybe this could work for multiline:

string target = 
    @"replace;
/*
* don't replace
*/
replace;
    ";

var output = Regex.Replace(target, @"(?<!./\*\s*)replace(?!\s*\*/)", "new string", RegexOptions.Singleline);

Console.WriteLine(output); 

output:

new string; /* * don't replace */ new string;


Just do a simple two-state scanner (REGULAR_TOKEN, COMMENT_TOKEN, ....)

Then for each REGULAR_TOKEN do a straightforward replace, and leave the comment_tokens. Once again I recommend Boost Spirit/

If you specified your goal/problem more, I might whip up an example

0

精彩评论

暂无评论...
验证码 换一张
取 消