正则表达式删除注释结尾
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
的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/
相关文章:
- Javascript中的备选注释方法
- html5视频中的Youtube类型注释
- 遍历 JSON 对象并检查 URL 是否以某个值结尾
- 如何允许在TinyMCE中使用valid_elements进行注释标记
- NodeJ中的注释会影响性能吗
- AngularJS指令模板开头的注释
- 如何用正则表达式替换特定的JavaScript注释
- 如何摆脱"压缩/块”;PHP页面底部的注释
- 删除LINES开头和结尾的空白
- 在if语句注释的条件内指定变量的值
- Visual Studio 2012:更改javascript注释样式
- 使用JQuery或Javascript编辑HTML注释文本
- 查找所有注释的JavaScript正则表达式
- 使用PrimeNG组件时出现问题(未找到指令注释)
- Angular http.get没有'我不喜欢在开头和结尾加方括号的文本文件
- 谷歌关闭注释赢得'Don’不要告诉我;I’我错了
- 检查整数是否以0结尾
- x-editable on按钮,如何编辑特定注释
- jQuery-选择以..开头和结尾的元素..但省略了具体名称
- 正则表达式删除注释结尾