Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 去掉C风格的多行注释_C#_Regex_Comments - Fatal编程技术网

C# 去掉C风格的多行注释

C# 去掉C风格的多行注释,c#,regex,comments,C#,Regex,Comments,我有一个C#string对象,它包含一个泛型方法的代码,前面有一些标准的C风格的多行注释 我想我可以使用System.Text.RegularExpressions删除注释块,但我似乎可以让它正常工作 我试过: code = Regex.Replace(code,@"/\*.*?\*/",""); 我能被指向正确的方向吗?你需要在星星出现之前避开你的反斜杠 string str = "hi /* hello */ hi"; str = Regex.Replace(str, "/\\*.*?\\

我有一个C#string对象,它包含一个泛型方法的代码,前面有一些标准的C风格的多行注释

我想我可以使用
System.Text.RegularExpressions
删除注释块,但我似乎可以让它正常工作

我试过:

code = Regex.Replace(code,@"/\*.*?\*/","");

我能被指向正确的方向吗?

你需要在星星出现之前避开你的反斜杠

string str = "hi /* hello */ hi";
str = Regex.Replace(str, "/\\*.*?\\*/", " ");
//str == "hi  hi"

使用RegexOptions.Multiline选项参数

string output = Regex.Replace(input, pattern, string.Empty, RegexOptions.Multiline);
完整示例

string input = @"this is some stuff right here
    /* blah blah blah 
    blah blah blah 
    blah blah blah */ and this is more stuff
    right here.";

string pattern = @"/[*][\w\d\s]+[*]/";

string output = Regex.Replace(input, pattern, string.Empty, RegexOptions.Multiline);
Console.WriteLine(output);

在正则表达式中使用反斜杠转义
*
,但也需要在C#字符串中转义这些反斜杠

因此,
@/\*.\*/”
“/\*.\*.\*/”

此外,注释应替换为空白,而不是空字符串,除非您确定自己的输入。

您可以尝试:

/\/\*.*?\*\//
由于正则表达式中有一些/,因此最好使用不同的分隔符,如:

#/\*.*?\*/#

我使用了逐字逐句操作符@,如果没有它,我以一种巧妙的方式提问会得到编译错误+1