簡體   English   中英

使用C#從字符串中刪除JavaScript注釋

[英]Remove JavaScript comments from string with C#

我試圖用C#從sting中刪除javascript注釋( ///**/ )。 有人有RegEx嗎? 我正在閱讀javascript文件列表,然后將它們附加到字符串並嘗試清理javascript代碼並輕松加載。 Bellow你會發現其中一個RegEx適用於/* */ comments但我也需要刪除//注釋:

content = System.Text.RegularExpressions.Regex.Replace(content,
    @"/\*[^/]*/", 
    string.Empty);

如果你想縮小Javascript文件(“輕松加載”),為什么不試試Douglas Crockford的JSMin呢? 頁面底部有鏈接到c#實現( http://www.crockford.com/javascript/jsmin.cs

您不能使用簡單的正則表達式從JS中刪除注釋 - 至少不可靠。 想象一下,例如,試圖處理像:

alert('string\' // not-a-comment '); // comment /* not-a-nested-comment
alert('not-a-comment'); // comment */* still-a-comment
alert('not-a-comment'); /* alert('commented-out-code');
// still-a-comment */ alert('not-a-comment');
var re= /\/* not-a-comment */; //* comment
var e4x= <x>// not-a-comment</x>;

你可以使你的正則表達式比現在更好地工作,使它以'* /'而不僅僅是'/'結束,並且在它周圍包裝一個or-clause,將//添加到新行的測試。 但它永遠不會是防彈的,因為正則表達式無法解析JavaScript或[X] HTML等語言。

Regex的替代品可以是.NetYUI Compressor ,它可以讓您刪除注釋並縮小JavaScript代碼。

// Note: string javaScript == some javascript data loaded from some file, etc.
compressedJavaScript= JavaScriptCompressor.Compress(javaScript); 

我推薦程序stripcmt

StripCmt是一個用C編寫的簡單實用程序,用於從C,C ++和Java源文件中刪除注釋。 在Unix文本處理程序的傳統中,它可以作為FIFO(先進先出)過濾器或在命令行上接受參數。

簡單而強大,工作完美無瑕。

content = Regex.Replace(content,
                        "/\\*.*?\\*/",
                        String.Empty,
                        RegexOptions.Compiled | RegexOptions.Singleline);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM