Соответствие коротким комментариям JavaScript (//) с ре

Я хотел бы отфильтровать (главным образом короткие) комментарии от (главным образом допустимого) JavaScript с помощью Python re модуль. Например:

// this is a comment
var x = 2 // and this is a comment too
var url = "http://www.google.com/" // and "this" too
url += 'but // this is not a comment' // however this one is
url += 'this "is not a comment' + " and ' neither is this " // only this

Я теперь пробую это в течение больше, чем получаса без любого успеха. Кто-либо может помочь мне?

РЕДАКТИРОВАНИЕ 1:

foo = 'http://stackoverflow.com/' // these // are // comments // too //

РЕДАКТИРОВАНИЕ 2:

bar = 'http://no.comments.com/'
6
задан Attila O. 26 January 2010 в 00:03
поделиться

2 ответа

Мои силы Regex были немного несвежены, поэтому я использовал ваш вопрос к свежему тому, что я помню. Он стал довольно большим регелем в основном, потому что я также хотел фильтровать многострочные комментарии.

import re

reexpr = r"""
    (                           # Capture code
        "(?:\\.|[^"\\])*"       # String literal
        |
        '(?:\\.|[^'\\])*'       # String literal
        |
        (?:[^/\n"']|/[^/*\n"'])+ # Any code besides newlines or string literals
        |
        \n                      # Newline
    )|
    (/\*  (?:[^*]|\*[^/])*   \*/)        # Multi-line comment
    |
    (?://(.*)$)                 # Comment
    $"""
rx = re.compile(reexpr, re.VERBOSE + re.MULTILINE)

Это регенсы совпадает с тремя разными подгруппами. Один для кода и два для комментариев содержимого. Ниже приведен пример того, как извлечь их.

code = r"""// this is a comment
var x = 2 * 4 // and this is a comment too
var url = "http://www.google.com/" // and "this" too
url += 'but // this is not a comment' // however this one is
url += 'this "is not a comment' + " and ' neither is this " // only this

bar = 'http://no.comments.com/' // these // are // comments
bar = 'text // string \' no // more //\\' // comments
bar = 'http://no.comments.com/'
bar = /var/ // comment

/* comment 1 */
bar = open() /* comment 2 */
bar = open() /* comment 2b */// another comment
bar = open( /* comment 3 */ file) // another comment 
"""

parts = rx.findall(code)
print '*' * 80, '\nCode:\n\n', '\n'.join([x[0] for x in parts if x[0].strip()])
print '*' * 80, '\nMulti line comments:\n\n', '\n'.join([x[1] for x in parts if x[1].strip()])
print '*' * 80, '\nOne line comments:\n\n', '\n'.join([x[2] for x in parts if x[2].strip()])
7
ответ дан 16 December 2019 в 21:39
поделиться

Это может быть легче разбираться, если у вас были явные полуобытия.

В любом случае, это работает:

import re

rx = re.compile(r'.*(//(.*))$')

lines = ["// this is a comment", 
    "var x = 2 // and this is a comment too",
    """var url = "http://www.google.com/" // and "this" too""",
    """url += 'but // this is not a comment' // however this one is""",
    """url += 'this "is not a comment' + " and ' neither is this " // only this""",]

for line in lines: 
    print rx.match(line).groups()

Выход вышеизложенного:

('// this is a comment', ' this is a comment')
('// and this is a comment too', ' and this is a comment too')
('// and "this" too', ' and "this" too')
('// however this one is', ' however this one is')
('// only this', ' only this')

Я не уверен, что вы делаете с JavaScript после , удаляя комментарии, но jsmin может помочь. В любом случае, он удаляет комментарии достаточно хорошо, и существует реализация в Python .

1
ответ дан 16 December 2019 в 21:39
поделиться
Другие вопросы по тегам:

Похожие вопросы: