【问题标题】:Regex for text between two static strings两个静态字符串之间文本的正则表达式
【发布时间】:2016-10-21 11:28:49
【问题描述】:

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

你好,

bla 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)"

【问题讨论】:

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

标签: regex vba email outlook special-characters


【解决方案1】:

听起来您需要匹配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+ 个非空白字符。

【讨论】:

  • 尽管正则表达式可以工作,但在此任务中使用InStr()Mid() 的组合会更快。应该不会太难做,因为分隔符是普通的固定字符串,而不是真正的模式。
  • 我也写了一个通用的article about extracting strings between two strings with regex,如果您在解决当前类似问题时遇到问题,请随时阅读。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多