使用python解析js中的多行注释

2024-04-26 11:39:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用python获取js文件中多行注释的内容。在

我试过这个代码示例

import re
code_m = """
/* This is a comment. */
"""
code_s = "/* This is a comment*/"

reg = re.compile("/\*(?P<contents>.*)\*/", re.DOTALL + re.M) 
matches_m = reg.match(code_m)
matches_s = reg.match(code_s)
print matches_s # Give a match object
print matches_m # Gives None

我得到matches_mNone。但是matches_s起作用了。我错过了什么?在


Tags: 文件代码renone示例内容ismatch
2条回答

^{}只在字符串开头匹配,请改用^{}。在

{cd4}的开头是一个{cd1}的字符串。在

作为补充说明,除非您在regex中使用^或{},并且希望它们在行的开头和结尾匹配,否则不需要re.M标志。在组合多个标志时,还应该使用按位或(re.S | re.M)而不是添加。在

re.match测试字符串是否与正则表达式匹配。您可能正在寻找re.search

>>> reg.search(code_m)
<_sre.SRE_Match object at 0x7f293e94d648>
>>> reg.search(code_m).groups()
(' This is a comment. ',)

相关问题 更多 >