我无法使用 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 组中捕获所需的输出:
(?=["'])(?:"[^"\\]*(?:\\[\s\S][^"\\]*)*"|'[^'\\]*(?:\\[\s\S][^'\\]*)*')|(#.*$)
使用回调函数替换的示例:
const regex = /(?=["'])(?:"[^"\\]*(?:\\[\s\S][^"\\]*)*"|'[^'\\]*(?:\\[\s\S][^'\\]*)*')|(#.*$)/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 脚本完成的 regex .
关于javascript - 如何使用regEx删除js中的python注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50535616/