Skip to main content
 首页 » 编程设计

python之Regex + Python之删除所有以 * 开头的行

2025年05月04日12jpfss

我想从给定文件中删除所有以 * 开头的行。例如,以下内容:

* This needs to be gone 
But this line should stay 
*remove  
* this too 
End 

应该生成这个:

But this line should stay 
End 

我最终需要做的是:

  1. 删除括号和括号内的所有文本(包括括号/括号),
  2. 如上所述,删除以 '' 开头的行。

到目前为止,我能够使用以下内容解决 #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) 

感谢大家的帮助。

请您参考如下方法:

使用正则表达式>>

s = re.sub(r'(?m)^\*.*\n?', '', s)  

检查 this demo .