Regex+Python-删除以*

2024-05-23 18:32:40 发布

您现在位置:Python中文网/ 问答频道 /正文

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

* 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)。我试了几次,但最后总是把我不想拿走的东西拿走


解决方案1(无regex)

>>> f = open('path/to/file.txt', 'r')
>>> [n for n in f.readlines() if not n.startswith('*')]

解决方案2(regex)

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

谢谢大家的帮助。


Tags: 文件toreline解决方案thisregexbut
3条回答

使用regex>;>

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

检查{a1}。

你不需要正则表达式。

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

相关问题 更多 >