Parse multiple comments from js file using python

时间秒杀一切 提交于 2020-01-05 07:55:12

问题


I want to get contents of a js file comments. I tried using the code

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")

The result I get is

This is a comment.
*/

/*
This is another comment.

How can I get the comments separately ?


回答1:


Make the repetition ungreedy:

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

Now the .* will consume as little as possible instead of as much as possible.

To get multiple matches you will want to use findall instead of search.



来源:https://stackoverflow.com/questions/13144883/parse-multiple-comments-from-js-file-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!