Parse multiple comments from js file using python

2019-07-26 03:51发布

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条回答
唯我独甜
2楼-- · 2019-07-26 04:22

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.

查看更多
登录 后发表回答