[英]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.