正则表达式移除特定行换行符:排除单独or行的实现方案
我有一个每段单独占一行的文本文件,部分段落被拆分到单词开头的位置,比如:
Books are an effective way to
communicate across time, both from the past and into the future.
原本想用正则表达式查找以小写字母开头的行,把前置的\r\n(回车+换行)替换成空格,但遇到章节副标题的场景时会出问题:
Chapter 3
The Importance of Reading
or
Literature is the most agreeable way of ignoring life
这种情况下,单独成行的"or"会被错误合并到章节标题里,我们需要保留这个独立行,最终要实现:匹配以小写字母开头的行并替换前置\r\n为空格,但排除内容为"or"的独立行。
正则表达式方案
查找规则
\r\n(?!or$)([a-z])
替换内容
$1
(注意替换内容开头有一个空格)
工具操作步骤
Notepad++
- 打开目标文本文件,按
Ctrl+H调出替换窗口 - 切换到「正则表达式」模式(别勾选".匹配换行符")
- 在「查找目标」框输入上面的正则表达式
- 在「替换为」框输入指定的替换内容
- 点击「全部替换」完成操作
Geany
- 打开目标文本文件,按
Ctrl+H调出替换窗口 - 勾选「使用正则表达式」选项
- 在「查找」框输入正则表达式
- 在「替换为」框输入指定的替换内容
- 点击「全部替换」执行操作
效果验证
拆分的段落会被正确合并:
原内容:Books are an effective way to
communicate across time, both from the past and into the future.
处理后:
Books are an effective way to communicate across time, both from the past and into the future.单独的"or"行完全保留:
原内容:Chapter 3
The Importance of Reading
or
Literature is the most agreeable way of ignoring life
处理后:
Chapter 3
The Importance of Reading
or
Literature is the most agreeable way of ignoring life
内容的提问来源于stack exchange,提问作者Dave Brunker

