且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如果它在Comments中,则删除行或字符串

更新时间:2023-11-07 19:35:04

)|(\ /*.*?* \ /) ;
return Regex.Replace(code,re,

1跨度>);
}


字符串 s = / * #define abcdef
#define ghijkl * /;


while(s.Contains(
#define))
{s = StripComments(s);}





这是正确的我感谢吗?谢谢


如果你正确地将其标记为

- 令牌,你只能以健壮的方式检测评论可以包含注释开始/结束字符序列(字符串,字符的所有瑕疵)

- 不能包含注释开始/结束字符序列的标记(除了上述标记和评论之外的所有标记)

- 行评论

- 阻止评论



您可以查看在C#中学习:字符,字符串,字符串格式,关键字,标识符 [ ^ ]在底部,查看用于使用正则表达式对C#进行标记的红利代码,包括行和块注释,并注意上述令牌。



干杯

Andi


Hi, i want to delete rows which has comments like "//" or "/*...*/" multile line or single line in C#

what i did is,

static string StripComments(string code)
 { var re = @"(^\/\/.*?$)|(\/*.*?*\/)";
 return Regex.Replace(code, re, "$1");
 }

In a Class
string s="/*#define abcdef
            #define ghijkl*/;
             

 while (s.Contains("#define"))
 {s= StripComments(s);}



is it correct what i did? thanks

)|(\/*.*?*\/)"; return Regex.Replace(code, re, "


1"); } In a Class string s="/*#define abcdef #define ghijkl*/; while (s.Contains("#define")) {s= StripComments(s);}



is it correct what i did? thanks


You can only detect comments in a robust way if you do properly tokenize into
- tokens that can contain comment start/end character sequences (all flawours of strings, characters)
- tokens that cannot contain comment start/end character sequences (all but the above tokens and but comments)
- line comments
- block comments

You may have a look at Escaping in C#: characters, strings, string formats, keywords, identifiers[^] at the bottom, see the bonus code for tokenizing C# with Regex, including line and block comments, taking in care of the above mentioned tokens.

Cheers
Andi