正则表达式删除注释结尾

时间:2015-05-30 04:19:05

标签: javascript regex

我正在尝试创建一个正则表达式,我可以使用它删除字符串中的任何结束注释语法。

例如,如果我有:

/* 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 -->

4 个答案:

答案 0 :(得分:8)

这应支持多种语言,包括不支持\s的bash:

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 "-->"
)

Demo 1

Demo 2

答案 1 :(得分:3)

您可以根据需要添加更多语言:

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

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

答案 2 :(得分:2)

Page.ClientScript.RegisterStartupScript(this.GetType(), "DisplayFunction", "AlertMessage('msg');", true);

请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

答案 3 :(得分:2)

    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/