You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用正则表达式将连续x个换行符替换为x-1个?

如何用正则表达式将连续x个换行符替换为x-1个?

看起来你踩了个常见的正则替换坑——你原来的写法会把所有2个及以上的换行直接缩成1个,但你真正要的是每连续x个换行就减少1个(比如3个变2个,2个变1个),对吧?

先帮你理清楚问题:你的原代码用re.sub(r'\n{2,}', '\n', text),这个正则的逻辑是“不管连续多少个换行(≥2),一律换成1个”,这就是为什么三个换行最后也变成了1个,和你的预期不符。

那怎么实现“连续x个→x-1个”的需求呢?其实很简单,我们可以利用Python正则的替换函数特性,根据匹配到的换行数量动态生成替换内容:

import re

def clean_text(text):
    # 匹配连续2个及以上的换行,然后替换成 长度-1 个换行
    return re.sub(r'\n{2,}', lambda match: '\n' * (len(match.group()) - 1), text)

咱们来测试你的例子:
原文本:

Anna lives in Latin America.\n\nShe loves the vibes from the cities\n and the good weather.\n\n\nAnna is great

用这个函数处理后,结果正好是你想要的:

Anna lives in Latin America.\nShe loves the vibes from the cities\n and the good weather.\n\nAnna is great

解释下这个写法的逻辑:

  • 正则r'\n{2,}'负责找到所有连续2个及以上的换行符组;
  • lambda match是一个匿名替换函数,每次匹配到一组换行,就拿到这组换行的长度(比如匹配到3个\n,长度就是3);
  • 然后生成长度-1个\n作为替换内容,完美实现“x个→x-1个”的效果。

如果你不想用lambda函数,也可以写个单独的替换函数,逻辑是完全一样的:

import re

def replace_newlines(match):
    return '\n' * (len(match.group()) - 1)

def clean_text(text):
    return re.sub(r'\n{2,}', replace_newlines, text)

这样就完全满足你的需求啦~

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.07 06:54:31