如何用一个删除单个新行来替换重复的新行?

How to replace repeated new lines with one removing single new lines?

我是 python 的新手。我正在尝试清理文本 正在寻找一个功能

  1. regex_replace('\n{2,}', '\n\n', text);
  2. regex_replace('\n', '', text);
sample = "he\nll\no\n\n\n\n My nam\ne is je\nff\n\nNew to Python";
#expected_output = "hello\n\nMy name is jeff\n\nNew to Python'

php similar problem

您可以将此正则表达式与交替和捕获组一起使用:

(\n\n)\n*|\n

替换为 </code> 以确保我们在超过 2 个换行符和只有 <code>\n.[= 时为空字符串的情况下得到 \n\n 17=]

RegEx Demo

代码:

import re

s = "he\nll\no\n\n\n\n My nam\ne is je\nff\n\nNew to Python"
print ( re.sub('(\n\n)\n*|\n', r'', s) )

输出:

hello

 My name is jeff

New to Python