的.
字符(默认设置)不匹配换行符。您需要通过设置re.DOTALL
flag来启用该功能。
>>> text = "line1\nline2\nstart\nline3\nline4\nline5\nline6\nend\nline7\nline8"
>>> print re.sub(r'start(.*)end', '', text, flags=re.DOTALL)
line1
line2
line7
line8
请注意,之间有一个空行;你需要包括换行符后end
太:
>>> print re.sub(r'start(.*)end\n', '', text, flags=re.DOTALL)
line1
line2
line7
line8
至于.
另外,您也可以使用两个对立的角色一起上课:
>>> print re.sub(r'start([\s\S]*)end\n', '', text)
line1
line2
line7
line8
这里\s
和\S
一起捕捉全部字符,包括换行符,没有设置DOTALL
标志。
你可能想让你的比赛不贪心。如果你有套start
和end
线在你的输入,那么.*
将从第一start
一路的所有文本匹配到最后end
:
>>> text = 'line1\nstart\nline2\nend\nline3\nstart\nline4\nend\nline5'
>>> print text
line1
start
line2
end
line3
start
line4
end
line5
>>> print re.sub(r'start(.*)end\n', '', text, flags=re.DOTALL)
line1
line5
注line3
是怎么没了。通过增加一个问号改变*
,使其成为非贪婪:
>>> print re.sub(r'start(.*?)end\n', '', text, flags=re.DOTALL)
line1
line3
line5
+1懒惰的量词。 –
正确工作。杰里你又救了我。:-)) –
@sundar_ima不客气:)考虑[接受](http://stackoverflow.com/help/accepted-answer)你认为为你工作的答案,以便将您的问题标记为已解决。 – Jerry