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

正则表达式替换:仅在无前后标点时将\n替换为句号

解决方案:根据上下文替换换行符\n

实现思路

  • 先匹配前后均无标点符号的\n,将其替换为句号(.)
  • 再将剩余所有\n(即前后存在任意标点的情况)替换为空字符串

代码实现(Python)

import re
import string

text = "This is a sample sentence with bullets:\n    Item 1\n    Item 2\nThis is the next sentence. This is the third sentence\n."

# 第一步:替换前后无标点的\n为句号
processed_text = re.sub(
    r'(?<![{}])(\n)(?![{}])'.format(re.escape(string.punctuation), re.escape(string.punctuation)),
    r'.',
    text
)
# 第二步:替换剩余的\n为空字符串
final_text = re.sub(r'\n', '', processed_text)

print(final_text)

运行结果

This is a sample sentence with bullets:    Item 1.    Item 2.This is the next sentence. This is the third sentence.

逻辑说明

  • string.punctuation包含所有常见标点符号,用re.escape处理避免正则语法冲突
  • (?<![{}])是反向否定断言,确保\n前不是标点;(?![{}])是正向否定断言,确保\n后不是标点
  • 分两步替换精准区分两种场景,完全匹配需求

内容的提问来源于stack exchange,提问作者Jenny Distel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 05:43:12