簡體   English   中英

正則表達式刪除注釋結尾

[英]Regex to remove comments endings

我正在嘗試創建一個正則表達式,我可以使用它來刪除字符串中的任何結束注釋語法。

例如,如果我有:

/* help::this is my comment */應該返回this is my comment<!-- help:: this is my other comment -->應該返回this is my other comment 理想情況下,我想針對需要結束注釋標記的所有主要編程語言。

這是我到目前為止:

function RemoveEndingTags(comment){
    return comment.split('help::')[1].replace("*/", "").replace("-->", ""); //my ugly solution
}

HTML標記示例如下:

<!-- help:: This is a comment -->
<div>Hello World</div>

所以字符串將是help:: This is a comment -->

這應該支持許多語言,包括不支持的\\s

help::[\r\n\t\f ]*(.*?)[\r\n\t\f ]*?(?:\*\/|-->)

你也可以使用它來阻止任何非必要的選擇,使這也更容易使用

help::[\r\n\t\f ]*(.*?)(?=[\r\n\t\f ]*?\*\/|[\r\n\t\f ]*?-->)

你可以使用它作為一個時髦的.replace但它可能導致古怪的行為:

/\/\*[\r\n\t\f ]*help::|<!--[\r\n\t\f ]*help::|[\r\n\t\f ]\*\/|[\r\n\t\f ]*-->/g

說明

解決方案1:

help::            Matches the text "help::"
[\r\n\t\f ]*      Matches any whitespace character 0-unlimited times
(.*?)             Captures the text
[\r\n\t\f ]*?     Matches all whitespace
(?:               Start of non-capture group
   \*\/           Matches "*/"
|                 OR
   -->            Matches "-->"
)                 End non capture group

[\\r\\n\\t\\f ]

\r Carriage return
\n Newline
\t Tab
\f Formfeed
   Space

解決方案2(幾乎支持一切)

help::             Matches "help::"
[\r\n\t\f ]*       Matches all whitespace 0-unlimited
(.*?)              Captures all text until...
(?=                Start positive lookahead
    [\r\n\t\f ]*?  Match whitespace 0-unlimited
    \*\/           Matches "*/"
|                  OR
    [\r\n\t\f ]*?  Match whitespace 0-unlimited
    -->            Matches "-->"
)

演示1

演示2

您可以根據需要添加更多語言:

help::.*?\s(.*)(?:.*?\s\*\/|.*?\s\-->)

示例: https//regex101.com/r/rK2kU0/1

var str = '<!-- A comment -->';
var newstr = str.replace(/<\!--(.*?)-->/, '$1');
console.log(newstr);  // A comment

請參閱https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

    var regExArray = [['\\/\\* help::','*/'],['<!-- help::','-->']]
var regexMatchers =  regExArray.map(function(item){
                        return new RegExp('^'+item[0]+'(.*)'+item[1]+'$')})

function RemoveEndingTagsNew(comment){
    var newComment;
    regexMatchers.forEach(function(regEx,index){
        if(regEx.test(comment)){
        newComment=comment.replace(/.* help::/,"").replace(regExArray[index][1],"")
       }
    });
    return newComment || comment;

}

它的版本較長,但如果開始和結束注釋標簽不匹配,則不會刪除注釋。

演示: https//jsfiddle.net/6bbxzyjg/2/

暫無
暫無

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

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