我需要一个正则表达式。它不需要很复杂,但必须涵盖所有基础。要求如下:
我被迫遵循的文件模式是一个文件看起来像这样:
chest/.setup.js
chest/**/*-chest.js
--choppers something:hello-there/wasup
--respite spoc
--chow ./chest//test.bootstrap#1
--chow ./chest/server.bootstrap#
--blow 200
我必须支持数以千计具有相似外观的其他文件。
我只想使用 //
或 #
之一来支持这些文件中的注释。
在使用正则表达式匹配进行处理之前,我的代码需要从文件内容中删除注释。
我还没有决定使用哪种注释语法(请不要将两者混为一谈,因为只会使用一种)。
注释可以在一行的开头(注释掉整行)或在同一行的末尾(注释掉它后面的所有内容)。
文件路径可能是“幼稚的”并且包含像这样的双斜杠.../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;
关于javascript - 我需要什么 JavaScript 正则表达式来区分注释和文件路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45742287/