2010-03-29 54 views
3

我有一個C#字符串對象,它包含一個通用方法的代碼,前面有一些標準的C-Style多行註釋。刪除C樣式多行註釋

我想我可以使用System.Text.RegularExpressions刪除評論塊,但我似乎能夠得到它的工作。

我想:

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

我可以在正確的方向指出?

+0

+1問這個問題很巧妙地 – Anonymoose 2010-05-12 09:06:05

回答

2

使用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); 
0

你需要在星星之前逃離你的反斜槓。

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

我使用了逐字運算符@,沒有它,我得到編譯錯誤 – Olaseni 2010-03-29 13:53:36

+0

@Olaseni:查看它編譯和工作的代碼示例。 – 2010-03-29 13:56:48

3

您正在使用反斜槓逃脫正則表達式*,但你還需要逃脫在C#字符串的反斜線完整的示例。

因此,@"/\*.*?\*/""/\\*.*?\\*/"

此外,評論應該有一個空格,而不是空字符串替換,除非你確信你的輸入。

0

你可以試試:

/\/\*.*?\*\// 

因爲有一些/正則表達式,它能夠更好地使用不同的分隔符爲:

#/\*.*?\*/#