1

假设我有这样的文字:

jessica\n\n\nhello\n\n\n\nhow are you doing?

如何使用正则表达式来确定是否有超过 2 个换行符,将其替换为最多 2 个换行符。

4

2 回答 2

6
>>> 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?'
>>>
于 2012-05-08T02:01:07.453 回答
4

另一个更简单,也许更容易理解的解决方案:

import re
foo = "jessica\n\n\nhello\n\n\n\nhow are you doing?"
re.sub('\n\n\n+', '\n\n', foo)
于 2012-05-08T02:54:24.277 回答