您可以使用一個正則表達式:
Regex rgx = new Regex(@"/\*.*?\*/");
string output = rgx.Replace(item,"");
當csharp
交互式控制檯運行此,我們得到:
csharp> using System.Text.RegularExpressions;
csharp> string item = "SET @rhsLclGrpVar = CAST(@variable1 AS CHAR(3)) /*RHS: X(03)*/+ CAST(@variable2 AS CHAR(42)) /*RHS: X(42)*/+ CAST(@variable3 AS CHAR(8)) /*RHS: X(08)*/";
csharp> Regex rgx = new Regex(@"/\*.*?\*/");
csharp> rgx.Replace(item,"");
"SET @rhsLclGrpVar = CAST(@variable1 AS CHAR(3)) + CAST(@variable2 AS CHAR(42)) + CAST(@variable3 AS CHAR(8)) "
正則表達式的工作原理如下:/\*
部分簡單地識別/*
模式。接下來.*?
匹配非貪婪任何字符序列,但會從匹配模式的下一部分即*/
片段的那一刻開始截斷。通過使用Replace
我們將替換爲所有與空字符串匹配的模式,因此我們將其刪除。
使用IndexOf
一個解決辦法是:
string result = item;
while(true) {
idx = result.indexof("/*");
if(idx >= 0) {
idx2 = result.indexof("*/",idx);
if(idx2 >= 0) {
result = result.Substring(0,idx)+result.Substring(idx2+2);
}
} else {
break;
}
}
但是,這是相當複雜(有仍然有一些bug一定的機率),將可能是低效率的。
還有其他選擇..但是,爲了簡單起見,怎麼樣..一個while循環,並且它發現索引/ *繼續? – BugFinder
正如BugFinder所建議的那樣:'int startIndex; while((startIndex = item.IndexOf(「/ *」)!= -1)' – xanatos
感謝您的建議,但我一直在尋找比while循環更清潔的東西,原因是這個代碼被嵌入在for循環中讀取文件。它可能會變得混亂 –