使用 Python 和正则表达式提取源代码中的C++注释

Extracting C++ comment in source code with Python and Regular Expression

本文关键字:C++ 注释 源代码 提取 Python 正则表达式 使用      更新时间:2023-10-16

我正在做一个项目,该项目要求我应该从C++源代码中提取注释,无论它位于何处。它可以是单行或多行注释。

我在txt文件中有以下内容作为数据输入,该文件已读入程序。

/* this is a comment in C. This comment syntax is guaranteed to work
on every compiler */ and
// This is also a comment in C. but it might present portability
challenges
Fortran
! This is a comment in Fortran
C++
// This is single Line Comment in C++
/* This is multi line comment.
in C++
*/

我的任务是提取人类可读的注释部分,不包括注释标签,因此使用 python 和正则表达式,下面是我的实现,我的 python 代码中有这个函数:

def cplusComment(self,content):
for comment in re.findall(r'/*((.*?)|(n))*/', content, re.S):
yield comment

上述函数在代码的这一部分中被调用:

def commentdata(self, content):
for con in content.read():
for k in self.cplusComment(con):
print(k, 'what is this k meant for')

我的输出是这种格式的空列表:

('', '', '')

我期待的应该是

this is a comment in C. This comment syntax is guaranteed to work
on every compiler
This is also a comment in C. but it might present portability
challenges
This is multi line comment in C++

如果我能引导到正确的方向,我将不胜感激

如果不构建一个完整的 C 解析器,你就无法可靠地解决这个问题,因为有字符串和嵌套的注释,并且/*序列可以很容易地在字符串内部,比如printf( "/* is this a comment or what?" );等。

此外,/**/有时用于注释掉部分代码,有时是相当大的块,而不用//注释每一行,这些代码块是您想要作为程序输出获得的注释吗?应该不会...

这里有一个链接,可能会让你朝着正确的方向前进: 纯 Python 中的完整 C99 解析器

lenik 是对的。但对于这个例子

pattern = re.compile('(?:/*(.*?)*/)|(?://(.*?)n)',re.S)
pattern.findall(s)

应该工作。