两个静态字符串之间文本的正则表达式

Regex for text between two static strings

我正在尝试从一系列电子邮件中提取文本。这些邮件看起来像:

Hello,

bla bla bla. The reason for this is: the problem was resolved after all

Kind regards,

bla bla

我有一个像这样的正则表达式:

With ReasonReg
    .Pattern = "(The reason for this is\s*:\s*)(\w\s*)+(?=\s*Kind regards)"
    .Global = False
    .IgnoreCase = False
End With

我的问题出现在使用数字和特殊字符(冒号和问号)的邮件中。 \w 与那些不匹配,当然,但是如果我尝试以下任一操作,我的 Outlook (Office 365) 将变得无响应。

.Pattern = "(The reason for this is\s*:\s*)(.*\s*)+(?=\s*Kind regards)"
.Pattern = "(The reason for this is\s*:\s*)(\w\W*\s*)+(?=\s*Kind regards)"
.Pattern = "(The reason for this is\s*:\s*)(\w[:?]*\s*)+(?=\s*Kind regards)"

听起来您需要匹配 The reason for this is\s*:\s*Kind regards 之间的所有内容。

您可以使用 [\s\S] 构造来匹配任何字符,并对其应用惰性量词 (*?) 以在第一个 Kind regards 之前匹配尽可能少的字符:

.Pattern = "(The reason for this is\s*:\s*)([\s\S]*?)(\s*Kind regards)"

regex demo

如果这些定界符之间有大量文本需要匹配,请考虑展开惰性匹配结构,例如:

(The reason for this is\s*:\s*)(\S*(?:\s(?!\s*Kind regards)\S+)*)(\s*Kind regards)
                                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

参见 another demo。此 \S*(?:\s(?!\s*Kind regards)\S+)* 模式匹配 0+ 个非空白字符 (\S*),后跟 0+ 个 1+ 个空白序列,后跟 Kind regards 和 1+ 个非空白字符。