简体   繁体   English

如何使用JavaScript正则表达式捕获CSS多行注释块

[英]How to capture a CSS multiline comment block with JavaScript regex

I'm trying to capture a CSS multiline comment block with a JavaScript regex but I'm not sure how to find the closing comment tag without get occasional slashes inside HTML examples, this is one case: 我正在尝试使用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>

*/

I'm trying with this regex but I arrive at the closing div tag: 我正在尝试这个正则表达式,但我到达结束div标签:

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

So I tryied adding the ending comment tag and it's just stop working: 所以我尝试添加结束注释标记,它只是停止工作:

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

How can I find a JavaScript regex to capture the entire block? 如何找到一个JavaScript正则表达式来捕获整个块?

Note that I can find more than one of these blocks per file, so I'll use the g tag on the regex. 请注意,我可以在每个文件中找到多个这样的块,因此我将在正则表达式中使用g标记。

Note that ([^\\*\\/]){1,} only matches 1 or more individual characters other than * or / , not as a sequence of 2 characters. 请注意, ([^\\*\\/]){1,}仅匹配除*/以外的1个或多个单个字符,而不是2个字符的序列。

You can use lazy matching ( *? quantifier matching as few characters as possible to ensure a match is found) with [^] or [\\s\\S] (classes that match any character including a newline): 您可以使用延迟匹配( *?量词匹配尽可能少的字符以确保找到匹配项)与[^][\\s\\S] (匹配包含换行符的任何字符的类):

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

See 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]); } 

I prefer [\\s\\S] to [^] as the latter is only supported by JavaScript regex engine. 我更喜欢[\\s\\S][^]因为后者只有JavaScript正则表达式引擎支持。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM