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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With