Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

/*@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:

\/\*@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?

Note that I can find more than one of these blocks per file, so I'll use the g tag on the regex.

like image 682
vitto Avatar asked Dec 07 '25 22:12

vitto


1 Answers

Note that ([^\*\/]){1,} only matches 1 or more individual characters other than * or /, not as a sequence of 2 characters.

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):

/\/\*@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.

like image 131
Wiktor Stribiżew Avatar answered Dec 10 '25 12:12

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!