I am trying to create a regex for detecting all the comments in a code.
But I am also getting the hyperlinks because of the inline comment characters sequence //, which I don't want; I just need the comment part.
var sample = `Hello //this is a test
http://google.com
//second
third
https://test.com`;
var regex = new RegExp(
/(\/\*([^*|[\r\n]|(\*+([^*\/]|[\r\n])))*\*+\/)|(\/\/.*)/g
);
console.log(sample.match(regex));
The output is ["//this is a test", "//google.com", "//second", "//test.com"]
The output should be ["//this is a test", "//second"]
For a quick and dirty way, you could use
(?<=^|[^\S])\/\/.+
In JavaScript, this could be
var sample = `Hello //this is a test
http://google.com
//second
third
https://test.com`;
var regex = new RegExp(/(?<=^|[^\S])\/\/.+/g);
console.log(sample.match(regex));
I added newline and 0 or more tabs before your two main capture groups:
/[\r\n][/t]*(\/\*([^*|[\r\n]|(\*+([^*\/]|[\r\n])))*\*\/)|[\r\n][\t]*(\/\/.*)/g
This means, the comment has to be at the beginning of a new line, so it wont match a hyperlink in the middle of your code.