1

I am currently trying to parse out comments in a particular format using JavaScript. While I have a basic understanding of regular expressions, with this one I seem to have reached my current limit. This is what I am trying to do:

The comments

//
    This is a
    multiline comment

Code here


//
    This is another
    comment

Again, code here

For the Regex, it currently looks this like this:

\/\/\n(\s+[\s\S]+)
  • \/\/\n matches the //sequence including the new line.
  • Since I am interested in the comments, I am opening a capture group.
  • \s+ matches the indentation. I could probably be a bit more precise by only accepting tabs or spaces in a particular count – for me this is not relevant
  • [\s\S] is supposed to match the actual words and and spaces between the words.

This seems to currently match the whole file, which is not what I want. What I now can't wrap my head around is how to solve this?

I think my problem is related to me not knowing how to think about regexes. Is it like a program that matches line per line, so I need to work more on the quantifiers? Or is there maybe a way to stop at lines only consisting of a newline? When I try to match for the newline character, I of course receive matches at each line ending, which is not helpful.

0

1 Answer 1

1

You may use

/^\/\/((?:\r?\n[^\S\r\n].*)*)/gm

See the regex demo

Details

  • ^ - start of a line (due to m modifier, ^ also matches line start positions)
  • \/\/ - a // string
  • ((?:\r?\n[^\S\r\n].*)*) - Capturing group 1: zero or more repetitions of
    • \r?\n - a CRLF or LF line ending
    • [^\S\r\n] - any whitespace but CR and LF
    • .* - the rest of the line.

JS demo:

var text = "//\n    This is a\n    multiline comment\n\nCode here\n\n\n//\n    This is another\n    comment\n\nAgain, code here";
var regex = /^\/\/((?:\r?\n[^\S\r\n].*)*)/gm, m, results=[];
while (m = regex.exec(text)) {
  results.push(m[1].trim());
}
console.log(results);

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

1 Comment

Thank you! With your answer I was able to understand RegExes A LOT better than before. It's like magic once you get the hang of it!

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.