正则表达式替换:仅在无前后标点时将\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
相关产品推荐
相关产品推荐

