[英]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
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
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 "-->"
)
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;
}
它的版本較長,但如果開始和結束注釋標簽不匹配,則不會刪除注釋。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.