javascript - 正则表达式删除评论结尾

标签 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 -->

最佳答案

这应该支持多种语言,包括 不支持 \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/

相关文章:

javascript - 更改具有相同 className 的某些 div 的样式

javascript - jquery javascript如何在文本区域后最近的div中显示一些html

regex - Powershell Parsing Help - 如何将文件夹名称列表输出到文本文件中

Java:分割逗号分隔的字符串但忽略引号中的逗号

javascript - 从 'onblur' 事件中排除表单按钮,JavaScript

javascript - 从 Backbone.js 中的项目列表渲染项目

javascript - 工具栏中不显示单选组按钮

java - 针对懒惰或贪婪的正则表达式所有格量词

Javascript正则表达式,如何允许页面值为空字符串进行打印

java - Java 中分隔符之间的多行文本匹配