Javascript Extract Comments RegExp

大兔子大兔子 提交于 2019-12-11 03:56:28

问题


I have a Javascript file like that

/**
 * My Comment Line1
 * My Comment Line2
 */
var a = 123;
/**
 * My Comment Line3
 * My Comment Line4
 */
var b = 456;

I am using node.js to read the file and want to extract comments in this file.

I use this regexp

/\/\*\*((?:\r|\n|.)*)\*\//

However this extracts

/**
 * My Comment Line1
 * My Comment Line2
 */
var a = 123;
/**
 * My Comment Line3
 * My Comment Line4
 */

My program have a loop to extract matched block one by one. So I want a RegExp to extract

First loop

/**
 * My Comment Line1
 * My Comment Line2
 */

Second loop

/**
 * My Comment Line3
 * My Comment Line4
 */

The rule is simply that comment block starts with /** and ends with */. Inside a comment, all characters are allowed.

Could anyone help me? Thanks!


回答1:


Try this : (it'll much ANY type of comments) - Live demo here : http://regexr.com?30jrh

(/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/)|(//.*)

Have a look :




回答2:


Here's a regular expression for that:

/\/\*\*(.|\n)+?\*\//

And here's a demo.




回答3:


The other answers did not quite work for me. Here's what did work, in Node.js, parsing Javascript.

/(\/\*([^*]|[\r\n]|(\*+([^*\/]|[\r\n])))*\*+\/)|(\/\/.*)/g



回答4:


/(\/\*).*?(\*\/)|(\/\/).*?(\n|\$)/s

Match opening and closing multiline tags and anything inbetween

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

Or match a single line open comment that is terminated by a new or end of line

(\/\/).*?(\n|\$)


来源:https://stackoverflow.com/questions/10098738/javascript-extract-comments-regexp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!