javascript - 将单行 JavaScript 注释 (//) 与 re 匹配

标签 javascript python regex replace

我想使用 python 的 re 模块从(大部分有效的)JavaScript 中过滤掉(大部分是单行的)注释。例如:

// 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/'

最佳答案

我的正则表达式能力有点过时了,所以我用你的问题来刷新我的内存。 它变成了一个相当大的正则表达式,主要是因为我还想过滤多行评论。

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()])

关于javascript - 将单行 JavaScript 注释 (//) 与 re 匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2136363/

相关文章:

javascript - 从 html 字符串中删除所有不需要的标签,但在 JS 中保留空格

python - BST 递归搜索保持返回 None

用于匹配文档 block 内的 JSDoc 标记的 Javascript 正则表达式

javascript - 使用动态键对嵌套对象进行分组(使用 Lodash)

javascript - 在 javascript 对象上计算相似的属性

python - 在 python/pygame 中使用箭头键使图像移动一格

python - 支持任意填充符的 python `str.zfill` 的通用版本?

mysql - Regexp 正则表达式,用于从 SELECT 查询中选择特定字符串模式

python - 如何在 Pandas 数据框单元格中提取部分字符串并在其中创建一个包含该字符串的新列

javascript - 为什么 IE 9 中图像不通过 CSS 参数旋转?