【问题标题】:How to do a multi-line any character match including newline character using RegEx in VBA如何在 VBA 中使用 RegEx 进行多行任何字符匹配,包括换行符
【发布时间】:2016-07-22 21:27:24
【问题描述】:

我正在尝试使用 VBA 中的正则表达式从 XML 中提取一些数据,方法是匹配元素的开始打开和关闭标记,但我什么也没得到。

我可以在 Notepad++ 中使用 <foo>.+?<\/foo>,但它不能在 Microsoft 正则表达式 5.5 的 VBA 中使用

<foo>
variable data here 
-
-
</foo>

【问题讨论】:

  • 你可以试试/&lt;foo&gt;[.\n\r]+?&lt;\/foo&gt;/gm

标签: regex vba excel string-matching multilinestring


【解决方案1】:

这是一个列出所有&lt;td&gt; 内容的示例:

Sub MatchXMLtags()
  Dim xml As String
  xml = "<td>a</td><td>b" & vbCrLf & "</td><td>c</td>" & vbCrLf & "<td>d</td>"

  Dim match As Object
  With CreateObject("VBScript.RegExp")
    .pattern = "<td>\s*([\S\s]+?)\s*</td>"
    .Global = True
    .IgnoreCase = True
    .MultiLine = False

    ' display the content of each td tag
    For Each match In .Execute(xml)
      Debug.Print match.SubMatches(0)
    Next
  End With
End Sub

【讨论】:

  • 这在 MS Word 中非常适合我(我测试的几十个中唯一的正则表达式),但不完全符合我的需要:作为起始分隔符,我有“##”,这很好;但我的结束分隔符是:§[text, text, text, text, ,,,]-(text, text, text,...),我不知道如何找到它;我什至无法为结束分隔符找到正确的正则表达式,我的输出是 all 文档中的分隔符!我尝试了 § [(.*)] - ((.*)) 和许多其他变体,但没有成功。
【解决方案2】:

这是因为 .在 VBA 中不包括换行符。 您可以在模式定义中使用 (.|\n)* 来包含换行符 \n 对于你的例子&lt;foo&gt;(.|\n)*&lt;\/foo&gt; 如果在 foo 块之间您不期望

【讨论】:

    猜你喜欢
    • 2011-03-14
    • 2010-11-12
    • 2016-07-31
    • 2012-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多