正则表达式删除注释结尾

Regex to remove comments endings

本文关键字:结尾 注释 删除 正则表达式      更新时间:2023-09-26

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

例如,如果我有:

/* 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的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 "-->"
)

演示 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/