【问题标题】:How to capture a CSS multiline comment block with JavaScript regex如何使用 JavaScript 正则表达式捕获 CSS 多行注释块
【发布时间】:2016-01-16 04:46:17
【问题描述】:

我正在尝试使用 JavaScript 正则表达式捕获 CSS 多行注释块,但我不确定如何在 HTML 示例中不偶尔出现斜杠的情况下找到结束注释标记,这是一种情况:

/*@comment

    @title: Buttons
    @name: block-name
    @category: Category name > Sub category
    @description: This is the description of the element
    @html:
        <div class="block-name"></div>

*/

我正在尝试使用这个正则表达式,但我到达了结束 div 标记:

\/\*@comment([^\*\/]){1,}

所以我尝试添加结束评论标签,它只是停止工作:

\/\*@comment([^\*\/]){1,}\*\/

如何找到一个 JavaScript 正则表达式来捕获整个块?

请注意,我可以在每个文件中找到多个这些块,因此我将在正则表达式上使用 g 标记。

【问题讨论】:

  • @MaxMastalerz 'a/*b*/c/*d*/'.match(/\/\*([^;]*)\*\//g) 生成 ["/*b*/c/*d*/"] 而不是 ["/*b*/", "/*d*/"]

标签: javascript html css regex node.js


【解决方案1】:

请注意,([^\*\/]){1,} 仅匹配 */ 以外的 1 个或多个单个字符,而不是 2 个字符的序列。

您可以对[^][\s\S](匹配包括换行符在内的任何字符的类)使用惰性匹配(*? 量词匹配尽可能少的字符以确保找到匹配项):

/\/\*@comment[\s\S]*?\*\//g

regex demo

var re = /\/\*@comment[\s\S]*?\*\//g; 
var str = '/*@comment\n\n    @title: Buttons\n    @name: block-name\n    @category: Category name > Sub category\n    @description: This is the description of the element\n    @html:\n        <div class="block-name"></div>\n\n*/';
var m;
 
while ((m = re.exec(str)) !== null) {
    if (m.index === re.lastIndex) {
        re.lastIndex++;
    }
    console.log(m[0]);
}

我更喜欢[\s\S] 而不是[^],因为后者仅受 JavaScript 正则表达式引擎支持。

【讨论】:

  • 你也可以使用带有缓和贪婪令牌的\/\*@comment(?:(?!\*\/)[\s\S])*\*\/ 正则表达式版本,但我怀疑你有什么理由在这里使用它,因为在匹配。
猜你喜欢
  • 2014-09-02
  • 1970-01-01
  • 2010-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-08
  • 2020-02-02
  • 2013-07-05
相关资源
最近更新 更多