我正在尝试创建一个正则表达式,我可以使用它从字符串中删除任何结束注释语法。
例如,如果我有:
/* 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
说明
解决方案一:
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
关于javascript - 正则表达式删除评论结尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30542194/