从文件中删除字符串中的单词,Python regex

2024-05-15 01:04:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在扫描一个C文件的文本,并在文件中搜索任何注释,注释在表单中。。你知道吗

/* this is a comment */

查找注释的正则表达式是

comment = r'\/\*(?:[^*]|\*[^/])*\*\/'

然后我做这个扫描文件并找到评论。。。你知道吗

for line in pstream:
            findComment = re.search(comment, line)
            if findComment:
                Comment = findComment.group(0)
                if isinstance(Comment, str):
                    print(Comment)
                if isinstance(line, str):
                    print(line)
                line = re.sub(Comment, "", line)
                print(line)

我想找到注释并从文件文本中删除它们。。你知道吗

但我对上述代码的输出是。。你知道吗

/* hello */
#include  /* hello */ "AnotherFile.h"
#include  /* hello */ "AnotherFile.h"

在第二次打印line时,我希望/* hello */不在那里,我假设这意味着注释已从文件中删除。。但是我的re.sub似乎对它没有任何作用。。你知道吗

有什么帮助吗?你知道吗

编辑: 我不知道为什么这两个#include印的颜色比较浅,但要澄清的是,它们的印法也和/* hello */一样

我用代码在另一个文件中测试了我的re.sub

import re

line = '#include /* hello */ "file.h"'
Comment = '/* hello */'

line = re.sub(Comment, " ", line)

print(line)

它会打印出来。。你知道吗

#include /* hello */ "file.h"

但我不想/* hello */在那里:(


Tags: 文件代码文本rehelloifincludeline
1条回答
网友
1楼 · 发布于 2024-05-15 01:04:01

我看到您正在使用Comment作为正则表达式。因为它可能(在本例中确实)包含特殊的regex元字符,所以需要re.escape它们。你知道吗

使用re.escape(Comment)

line = re.sub(re.escape(Comment), "", line)

demo

第二个print的输出现在与预期一样:

/* hello */
#include  /* hello */ "AnotherFile.h"
#include   "AnotherFile.h"

要确保删除初始空格,可以在开头(see demo)附加r"\s*"

line = re.sub(r"\s*" + re.escape(Comment), "", line)

相关问题 更多 >

    热门问题