【问题标题】:Parse multiple comments from js file using python使用python从js文件中解析多个注释
【发布时间】:2012-10-20 03:21:51
【问题描述】:

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

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.

如何分别获得 cmets ?

【问题讨论】:

    标签: javascript python regex comments


    【解决方案1】:

    使重复不贪婪:

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

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

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

    【讨论】:

    • 它只给了我第一条评论。我怎样才能得到两个 cmets ?感谢您的提示。
    • 使用findall 而不是search
    • 会处理嵌入式 cmets 吗?
    • @grieve 抱歉,什么是嵌入式 cmets?
    • @grieve 不会。这就是为什么正则表达式通常不足以解析编程语言。
    猜你喜欢
    • 2012-10-20
    • 2014-03-03
    • 1970-01-01
    • 1970-01-01
    • 2017-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-17
    相关资源
    最近更新 更多