使用 Python 和正则表达式提取源代码中的C++注释
Extracting C++ comment in source code with Python and Regular Expression
我正在做一个项目,该项目要求我应该从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)
应该工作。
相关文章:
- Visual Studio 2019:插入多个C++风格的单行注释
- VSCode 中带有 C/C++ 扩展名的多行注释缩进错误
- 如果我注释掉换行符,为什么'string'会成为一个不合格的变量
- 为什么 ## aka 令牌粘贴运算符不适用于 C 和 C++ 中的注释?
- 在 // C++注释中使用 \\ 是否合法?(C++评论中的LaTeX方程)
- 注释一行使代码工作,而没有它,代码不起作用
- 使用 Doxygen 在不同文件中注释函数
- 如何设置叮当格式的注释编译指示,以免触及多行doxygen注释?
- Qt - 带有注释的 JSON
- Visual Studio Community 代码分析的质量与 SAL 注释
- 如何阻止 ReSharper 在 C++ 中格式化多行注释
- C++,在多行代码段中注释
- 使用 Python 和正则表达式提取源代码中的C++注释
- 使用 C++ std::sregex_token_iterator 提取 HTML 注释
- C(嵌入式):注释 FreeRTOS 的 RootTask 时代码大小不会缩小
- 我需要帮助创建一个评分系统,但它一直给我一个错误,注释掉的整数是给我带来麻烦的部分
- 如何确保 C/C++ 代码中不会缺少 doxygen 风格的文档注释?
- 删除被注释掉的代码,而不是实际的赞美
- Cpp检查规则不显示 #define,注释
- Visual Studio 2017 是否有用于创建单行注释的特定键盘组合?