0

I want to write a function that takes a string and returns an array with the content of all the block comments from it. For example:

var text = 'This is not a comment\n/*this is a comment*/\nNot a comment/*Another comment*/';
var comments = getComments(text);

And 'comments' will be an array with the values:

['this is a comment', 'Another comment']

I tried with this code:

function getComments(text) {
    var comments,
    comment,
    regex;

    comments = [];
    regex = /\/\*([^\/\*]*)\*\//g;
    comment = regex.exec(text);

    while(comment !== null) {
        skewer.log(comment);
        comments.push(comment[1]);
        comment = regex.exec(text);
    }

    return comments;
}

The problem is that if there is a * or a / inside the comment, it does not match

3 Answers 3

1

I'm not sure about the JavaScript piece, but this regex should match your pattern: \/\*.*?\*\/

Sign up to request clarification or add additional context in comments.

Comments

0

I updated your code a bit in this jsfiddle, removing some of the ancillary code (like skewer). Here is the relevant part:

function getComments(text) {
    var comments,
    regex,
    match;
    comments = [];
    regex = /\/\*.*?\*\//g

    while ((match = regex.exec(text)) != null) {
        comments.push(match);
    }
    return comments;
}

1 Comment

This only works with most but not all the cases. Take var a = "/*"; var b = "*/"; for example - no comment should be extracted.
0

Try this solution, works on php and javascript:

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

You can test on: https://regex101.com/r/qoeQLq/2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.