我对 python 比较陌生,我需要打印 C 程序中使用的多行注释。 我有一个 test.c 文件,如下所示:
/* print multiline
comments */
我尝试了以下Python代码来解析C代码并打印多行注释
import re
fileopen = open('test.c', 'rw')
for var in fileopen:
if var.startswith("/*"):
var1 = re.sub(r'\n', " ", var)
var1 = var.rstrip()
print var1
我得到的输出是:
/* print multiline
即使我用空格替换换行符,注释的第二行也不会被打印。 请在这方面帮助我。
最佳答案
如果您唯一的要求是查找跨多行的注释,那实际上非常简单。就像这样:
for match in re.finditer(r"\/\*(.*\n.*)\*\/", code, re.MULTILINE):
print match.group(1)
重要的部分是:
\/\*(.*\n.*)\*\/
它查找文字 /*
、任意数量的字符、换行符、任意数量的字符和文字 */
,并捕获注释分隔符之间的部分.
此外,标志 re.MULTILINE
允许正则表达式搜索跨行搜索,这使我们能够强制它必须是多行注释。
full code can be run on codepad.org :
code= """/* print multiline
comments */
// One line comment
/* Another one line comment */
/* Multiline
comment */
"""
import re
for match in re.finditer(r"\/\*(.*\n.*)\*\/", code, re.MULTILINE):
print match.group(1)
这给出:
print multiline
comments
Multiline
comment
关于Python:用多行注释之间的空格替换换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23601790/