我无法使用 javascript 正则表达式从源代码中删除 python 注释,并且通常排除内联注释(不包括字符串(
的负面展望我试过的是这个
正则表达式:/#.*(?!')/gi
测试文件:
class AAA:
"""
item
"""
''''
SRC_TYPE = (
('cs', 'src C# for all'), # this is a comment a 'comment'
('cpp', 'C++'),
('ascript', 'a '),#djshdjshdjshds
('script', 'tst C#')
)
但不起作用
这很棘手。我建议使用垃圾桶方法,在完整匹配中扔掉所有不需要替换的内容,并在第 1 组中捕获所需的输出:
(?=["'])(?:"[^"\]*(?:\[sS][^"\]*)*"|'[^'\]*(?:\[sS][^'\]*)*')|(#.*$)
演示
使用替换为回调函数的示例:
const regex = /(?=["'])(?:"[^"\]*(?:\[sS][^"\]*)*"|'[^'\]*(?:\[sS][^'\]*)*')|(#.*$)/gm;
const str = `class AAA:
"""
item
"""
''''
SRC_TYPE = (
('cs', 'src C# for all'), # this is a comment a 'comment'
('cpp', 'C++'),
('ascript', 'a '),#djshdjshdjshds
('script', 'tst C#')
)`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, function(m, group1) {
if (group1 == null ) return m;
else return "";
});
console.log('Substitution result: ', result);
困难的部分是由Casimir et Hippolyte的ECMA脚本正则表达式完成的。