如何用RegEx匹配Description:与Send file:间的所有字符(含换行)
正则表达式捕获指定区间文本问题
需求
仅捕获Description:与Send file:之间的所有文本及换行符。
示例文本
Summary: Mr. Darcy drew his chair a little towards her, and said, “You cannot have a righ
Description: A short dialogue on the subject of the country ensued, on either side calm and concise--and soon put an end to by the entrance of Charlotte and her sister, just returned from her walk. The tete-a-tete surprised them. Mr. Darcy related the mistake which had occasioned his intruding on Miss Bennet, and after sitting a few minutes longer without saying much to anybody, went away.
Send file: No
Needed: Within 10 business days
已尝试正则
- 正则1:
Description:\s(.*\n?(?=\nSend file:))
- 正则2:
Description:\s(.*\n(?=Send file:))
问题分析
你用的正则存在两个核心问题:
.*默认不匹配换行符,如果Description:后的内容跨多行,会直接中断捕获;- 硬加
\n?或\n的写法过于死板,要么可能多捕换行,要么漏捕内容本身带换行的情况。
解决方案
根据不同的正则环境,有两种可靠写法:
方案1:启用单行模式(DOTALL)
大部分正则引擎支持单行模式(让.匹配包括换行在内的所有字符),用非贪婪匹配确保精准捕获:
Description:\s(.*?)(?=\nSend file:)
.*?:非贪婪匹配任意字符,直到遇到后面的\nSend file:停止;(?=\nSend file:):正向预查,确保捕获的内容是Send file:行的前一段,不会包含Send file:本身。
方案2:不依赖单行模式(通用写法)
如果环境不支持单行模式,用[\s\S]代替.匹配所有字符(空白+非空白=所有字符):
Description:\s([\s\S]*?)(?=\nSend file:)
这个写法兼容性更强,不需要额外开启模式,效果和方案1一致。
内容的提问来源于stack exchange,提问作者GWCO
相关产品推荐
相关产品推荐

