Alex Yeung
Alex Yeung

Reputation: 2515

Javascript Extract Comments RegExp

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!

Upvotes: 2

Views: 3593

Answers (4)

Mwayi
Mwayi

Reputation: 1623

/(\/\*).*?(\*\/)|(\/\/).*?(\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|\$)

Upvotes: 0

ruffrey
ruffrey

Reputation: 6128

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

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

Upvotes: 0

Ry-
Ry-

Reputation: 224903

Here's a regular expression for that:

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

And here's a demo.

Upvotes: 2

Dr.Kameleon
Dr.Kameleon

Reputation: 22820

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

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

Have a look :

enter image description here

Upvotes: 6

Related Questions