假设我有这样的文字:
jessica\n\n\nhello\n\n\n\nhow are you doing?
如何使用正则表达式来确定是否有超过 2 个换行符,将其替换为最多 2 个换行符。
>>> import re
>>> foo = "jessica\n\n\nhello\n\n\n\nhow are you doing?"
>>> re.sub('(\n{1,2})\n*', '\g<1>', foo)
'jessica\n\nhello\n\nhow are you doing?'
>>>
另一个更简单,也许更容易理解的解决方案:
import re
foo = "jessica\n\n\nhello\n\n\n\nhow are you doing?"
re.sub('\n\n\n+', '\n\n', foo)