简体   繁体   中英

how remove python comment in js using regEx

I'm not able to remove python comment from source, using javascript regular expression, and negative lookahead in general exclude an inline comment, excluding string

what I've tried is this

regex: /#.*(?!')/gi

test file:

class AAA:
    """
        item
    """
     ''''
    SRC_TYPE = (
        ('cs', 'src C# for all'),       # this is a comment a 'comment'
        ('cpp', 'C++'),
        ('ascript', 'a  '),#djshdjshdjshds
        ('script', 'tst C#')
    )

but don't works

This is tricky. I suggest using the trash-can approach and throw everything that does not need to be replaced in the full match and capture the desired output in group 1:

(?=["'])(?:"[^"\\]*(?:\\[\s\S][^"\\]*)*"|'[^'\\]*(?:\\[\s\S][^'\\]*)*')|(#.*$)

Demo

Sample using replace with callback function:

 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); 

The hard part is done by Casimir et Hippolyte's ECMA script regex .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM