我正在扫描一个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 */
在那里:(
我看到您正在使用
Comment
作为正则表达式。因为它可能(在本例中确实)包含特殊的regex元字符,所以需要re.escape它们。你知道吗使用
re.escape(Comment)
:见demo
第二个
print
的输出现在与预期一样:要确保删除初始空格,可以在开头(see demo)附加
r"\s*"
:相关问题 更多 >
编程相关推荐