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

时间:2018-08-11 06:22:01

标签: python c++ regex

我正在从事一个项目,该项目要求无论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++
    */

我的任务是提取不包括comment标签的可读注释部分,因此使用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++

如果能正确地指导我,我将不胜感激

2 个答案:

答案 0 :(得分:2)

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

此外,/**/有时用于注释掉部分代码,有时是相当大的块,而没有用//注释每一行,这些代码会阻止您的注释想要得到您的程序输出?可能不是...

以下链接可能会帮助您朝正确的方向前进:Complete C99 parser in pure Python

答案 1 :(得分:0)

莱尼克是对的。但是对于这个例子

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

应该工作。