我想使用 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/