How can I find multi-line JavaScript comment blocks using regex?

I am trying to pull blocks of code comments from JavaScript files. I am creating a document with light code.

Example:

/** @Method: setSize * @Description: setSize DESCRIPTION * @param: setSize PARAMETER */ 

I need to pull comment settings like this, ideally in an array.

I got to this, but I understand that it cannot handle newline tabs, etc .:

 \/\*\*(.*?)\*\/ 

(Well, that sounds like it would be simple, but I'm going in circles trying to get it to work.)

+4
source share
3 answers

Depending on what you want to continue with the extracted doc blocks, many different approaches come to mind. If you just need dockblocks without further reference, String.match () may be enough. Otherwise, you may need a block index.

As others have already pointed out, javascript RegEx is everything but powerful. if youโ€™re used to PCRE, itโ€™s like working with your hands behind your back. [\s\S] (space-character, non-space-character) is equivalent to dotAll - also captures line breaks.

This should help you:

 var string = 'var foo = "bar";' + '\n\n' + '/** @Method: setSize' + '\n * @Description: setSize DESCRIPTION' + '\n * @param: setSize PARAMETER' + '\n */' + '\n' + 'function setSize(setSize) { return true; }' + '\n\n' + '/** @Method: foo' + '\n * @Description: foo DESCRIPTION' + '\n * @param: bar PARAMETER' + '\n */' + '\n' + 'function foo(bar) { return true; }'; var docblock = /\/\*{2}([\s\S]+?)\*\//g, trim = function(string){ return string.replace(/^\s+|\s+$/g, ''); }, split = function(string) { return string.split(/[\r\n]\s*\*\s+/); }; // extract all doc-blocks console.log(string.match(docblock)); // extract all doc-blocks with access to character-index var match; while (match = docblock.exec(string)) { console.log( match.index + " characters from the beginning, found: ", trim(match[1]), split(match[1]) ); } 
+4
source

This should capture the comment block \/\*\*[^/]+\/ . I don't think Regexp is the best way to generate an array from these blocks. This regex basically says:

Find a /** (asterisk and slashes with screens are escaped with \ )

then find everything that is not /

then find one /

This is rude, but usually should work. Here is a live example http://regexr.com?300c6

+1
source

How about some kind of magic :)

 comment.replace(/@(\w+)\s*\:\s*(\S+)\s+(\w+)/gim, function (match, tag, name, descr) { console.log(arguments); // Do sth. ... }); 

I have not tested it this way for regular expression, there is no guarantee, just to point you to the possibility of some RegExp search in the method of John Resig 8 -)

0
source

Source: https://habr.com/ru/post/1396222/


All Articles