[英]Regex + Python - Remove all lines beginning with a *
我想從給定文件中刪除所有以*開頭的行。 因此,例如,以下內容:
* This needs to be gone
But this line should stay
*remove
* this too
End
應該產生這個:
But this line should stay
End
我最終需要做的是:
到目前為止,我可以使用以下地址尋址#1: re.sub(r'[.?]|(.*?)', '', fileString)
。 我為#2嘗試了幾件事,但總是最終刪除了我不想刪除的東西
解決方案1(無正則表達式)
>>> f = open('path/to/file.txt', 'r')
>>> [n for n in f.readlines() if not n.startswith('*')]
解決方案2(正則表達式)
>>> s = re.sub(r'(?m)^\*.*\n?', '', s)
謝謝大家的幫助。
您不需要正則表達式。
text = file.split('\n') # split everything into lines.
for line in text:
# do something here
讓我們知道您是否需要更多幫助。
您確實應該在此處提供更多信息。 至少,您要使用什么版本的python和一個代碼片段。 但是,也就是說,為什么需要一個正則表達式? 我不明白為什么您不能只使用startswith。
以下內容適用於Python 2.7.3
s = '* this line gotta go!!!'
print s.startswith('*')
>>>True
>>> f = open('path/to/file.txt', 'r')
>>> [n for n in f.readlines() if not n.startswith('*')]
['But this line should stay\n', 'End\n']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.