Skip to main content
 首页 » 编程设计

javascript之使用python从js文件中解析多个注释

2025年05月04日24linjiqin

我想获取一个js文件的评论内容。我尝试使用代码

import re 
code = """ 
/* 
This is a comment. 
*/ 
 
/* 
This is another comment. 
*/ 
 
""" 
reg = re.compile("/\*(?P<contents>.*)\*/", re.DOTALL) 
matches = reg.search(code) 
 
if matches: 
    print matches.group("contents") 

我得到的结果是

This is a comment. 
*/ 
 
/* 
This is another comment. 

如何单独获取评论?

请您参考如下方法:

使重复变得不贪婪:

"/\*(?P<contents>.*?)\*/" 

现在 .* 将消耗尽可能少而不是尽可能多。

要获得多个匹配项,您需要使用 findall而不是 search。