簡體   English   中英

正則表達式匹配模式,然后從文本文件中刪除它

[英]regex to match a pattern and then delete it from a text file

我目前面臨一個問題。 我正在嘗試編寫正則表達式代碼以匹配文本文件中的模式,並在找到它后,將其從當前文本中刪除。

 # Reading the file data and store it with open('file.txt','r+') as f: file = f.read() print(file)

這是我打印時的文字

'{\n\tINFO\tDATA_NUMBER\t974\n\t{\n\t\tDAT_CQFD\n\t\t{\n\t\t\tsome random text \t787878\n\t\t}\n\t\tDATA_TO_MATCH\n\t\t{\n\t\t1\tbunch of characters \t985\n\t\t2\tbunch of data\t\t78\n\t\t}\n\t}\n\tINFO\tDATA_CATCHME\t123\n\t{\n\t\t3\tbunch of characters \n\t\t2\tbunch of datas\n\t}\n\tINFO\tDATA_INTACT\t\t456\n\t{\n\t\t3\tbunch of numbers \n\t\t2\tbunch of texts\n\t}\n\n'

這是用編輯器打開的相同文本的圖片: image here I would like to match / search DATA_TO_MATCH 然后查找最后一個右括號“}”並刪除此右括號和包含的下一個括號之間的所有內容。 我想對 DATA_CATCHME 做同樣的事情。

這是預期的結果:

 '{\n\tINFO\tDATA_NUMBER\t974\n\t{\n\t\tDATA_CQFD\n\t\t{\n\t\t\tsome random text \t787878\n\t\t}\n\n\t}\n\tINFO\tDATA_INTACT\t\t456\n\t{\n\t\t3\tbunch of numbers \n\t\t2\tbunch of texts\n\t}\n\n}\n'

這是使用編輯器打開的相同文本結果的圖片: image here

我嘗試了一些

import re #find the DATA_TO_MATCH re.findall(r".*DATA_TO_MATCH",file) #find the DATA_CATCHME re.findall(r".*DATA_CATCHME",file) #supposed to find everything before the closed bracket "}" re.findall(r"(?=.*})[^}]*",file)

但是我對 regex 和 re 不是很熟悉,我無法從中得到我想要的,我想當它被發現時我會使用

re.sub(my_patern,'', text)

從我的文本文件中刪除它

這里的主要技巧是使用re.MULTILINE標志,它將跨行。 您還應該直接使用re.sub而不是re.findall

一旦你理解了正則表達式本身就很簡單。 您在DATA_TO_MATCH之前查找任何字符,然后咀嚼任何可能存在的空格(因此* ),讀取{ ,然后讀取所有不是}的字符,最后使用} 對於第二個,這是一個非常相似的策略。

 import re with open('input.txt', 'r+') as f: file = f.read() # find the DATA_TO_MATCH file = re.sub(r".*DATA_TO_MATCH\s*{[^}]*}", "", file, flags=re.MULTILINE) # find the DATA_CATCHME file = re.sub(r".*DATA_CATCHME[^{]*{[^}]*}", "", file, flags=re.MULTILINE) print(file)

暫無
暫無

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

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