Python:用多行注释之间的空格替换换行符

标签 python regex

我对 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/

相关文章:

c++ - 用于封装 v4 子网掩码和 v6 前缀长度的正则表达式

regex - 将字符串截断至 PCRE 中的大小

c# - 如何在C#中逐行读取?

python - 从 biopython 远程爆破

Python:找到最小元素的最后一个索引?

python - 从图像中删除边框但保留文字写在边框上(OCR 之前的预处理)

C# 正则表达式 替换字符串中的所有匹配项

java - 用于从完整文件位置提取路径的正则表达式

python - 允许重复键的 python 中的 BTree 实现?

Python:防止字典的键被覆盖