我需要什么 JavaScript 正则表达式来区分注释和文件路径?

What JavaScript regex do I need to distinguish between a comment and a file path?

我需要一个正则表达式。它不需要很复杂,但必须涵盖所有基础。要求如下:

我被迫遵循的文件模式是这样的,文件如下所示:

chest/.setup.js
chest/**/*-chest.js
--choppers something:hello-there/wasup
--respite  spoc
--chow ./chest//test.bootstrap#1
--chow ./chest/server.bootstrap#
--blow 200

我必须支持数千个具有相似外观的其他文件。

我想仅使用 //# 之一来支持这些文件中的评论。

在使用正则表达式匹配进行处理之前,我的代码需要从文件内容中删除注释。

我还没有决定使用哪种注释语法(请不要将两者混为一谈,因为只会使用一种)。

注释可以在一行的开头(注释掉整行),也可以在同一行的末尾(注释掉后面的所有内容)。

文件路径可能是 "naive" 并且包含双斜杠,例如... /path//to/file/example.js

另请记住,# 是有效的文件名字符,文件名在某些操作系统上可以包含空格。

我的问题是:

(1) 如果我使用 // 语法,需要什么正则表达式来删除注释?

(2) 如果我使用 # 语法,需要什么正则表达式来删除注释?

请随意回答 (1) 或 (2) 或两个,但不要一起回答。

如果您觉得我还有什么需要注意的地方,请指教。 ES5 语法中首选的答案(一个恼人的限制)。

要避免以 -- 开头的行,您可以使用此正则表达式模式。

var noDoubleDashComments = /^(?!\s*--).*$/gm;

^ : Matches the beginning of the string, or the beginning of a line if the multiline flag (m) is enabled. This matches a position, not a character.

(?!\s*--) : a negative lookahead to avoids lines that start with 0 or more whitespaces followed by 2 daches

.*$ : any character till the end of the line

Flags

g : global search. To find all occurences instead of only the first.

m : When the multiline flag is enabled, beginning and end anchors (^ and $) will match the start and end of a line, instead of the start and end of the whole string.

其他评论风格:

var noDoubleForwardSlashComments = /^(?!\s*\/{2}).*$/gm;

var noHashComments = /^(?!\s*#).*$/gm;

var noHashOrDashOrSlashComments = /^(?!\s*(?:\/\/|--|#)).*$/gm;

是否有文本后跟双短划线注释的行?
例如:

it's over 9000 -- DBZ reference

您可以使用类似下面的内容来仅获取评论之前或行尾的文本:

var noDoubleDashCommentsAtAll = /^(?!\s*--).+?(?=\s*--|$)/gm;