簡體   English   中英

從文件python正則表達式中刪除字符串中的單詞

[英]Deleting a word in a string from a file, Python regex

我正在掃描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作為正則表達式。 由於它可能(並且在這種情況下確實 )包含特殊的正則表達式元字符,因此您需要重新轉義它們。

使用re.escape(Comment)

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

觀看演示

現在第二張print的輸出符合預期:

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

為了確保刪除了初始空格,可以在開頭添加r"\\s*"請參見demo ):

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM