javascript - 如何使用regEx删除js中的python注释

标签 javascript regex python-3.x

我无法使用 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][^'\\]*)*')|(#.*$)

Demo

使用回调函数替换的示例:

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/

相关文章:

javascript - 为什么使用 .html() 会破坏这个 Replace 表达式?

python - geopandas 和 geopy 的地理编码错误

javascript - 在 Chrome 浏览器中尝试从同一窗口中的另一帧刷新一帧

python - Urls.py 无法将 #(pound) 字符传递给 Django 中的 View ,

python - 在Python中使用正则表达式分隔符分割字符串

python-3.x - 无法对未注册的加载程序类型执行此操作

Python3 json.dumps 给出 TypeError : keys must be a string

javascript - 使用 AJAX 请求时还需要 Form 元素吗?

javascript - 因此 Origin 'http://localhost:3000' 不允许访问 Twitter API

javascript - 动画 <tr> 的大小