VBA 正则表达式无法读取字符串



我创建了一个VBA宏,它能够找到以下字符串的可能性。

With mainSel.Find
    .ClearFormatting
    .MatchWildcards = True
    .Text = "[{[][a-zA-Z0-9,.:-;^l^13 ]@[}]]"
    .Wrap = wdFindContinue
End With
  • {xxxxx}
  • { xxxx }
  • {xxx }
  • {xxxx, xxxx}
  • { xxxx,xxxx}
  • {xxxx,xxxx }
  • { xxxx, xxxx }

但目前的情况是,当它在文档中找到字段代码时,它会跳过所有其他匹配项。如果我删除上面正则表达式中的空格,它正在处理域代码之后的字符串,但它会跳过其中有空格的字符串,例如 { xxxx}。

例如:这是一个示例 {xxxx} -get processing。这是 [fieldcode]。 这是未被处理的字符串{xxx}。

您需要

一个 while 循环来循环出现,因为如果查找操作成功,Execute返回True

Option Explicit
Sub TestFind()
    Dim Content As Range
    Dim i As Long
    Set Content = ActiveDocument.Content
    ' let's print what we got so far
    Debug.Print "All text is:" & vbNewLine & Content.Text
    With Content.Find
        .ClearFormatting
        ' our find loop
        Debug.Print "Occurences: "
        While .Execute(MatchWildcards:=True, Wrap:=wdFindStop, FindText:="[{[][a-zA-Z0-9,.:-;^l^13 ]@[}]]")
            ' count occurences
            i = i + 1
            ' lets bold text just for testing purposes
            Content.Bold = True
            ' and also print each occurence
            Debug.Print vbTab & "Occurence #" & i & vbTab & Content.Text
        Wend
    End With
End Sub

输出:

All text is:
{xxxxx} 
asdasd
{ xxxx } 
As{asd}
asff
{xxx } 
{xxxx, xxxx} 
safasf
{ xxxx,xxxx} 
{xxxx,xxxx } 
{ xxxx, xxxx }

Occurences: 
    Occurence #1    {xxxxx}
    Occurence #2    { xxxx }
    Occurence #3    {asd}
    Occurence #4    {xxx }
    Occurence #5    {xxxx, xxxx}
    Occurence #6    { xxxx,xxxx}
    Occurence #7    {xxxx,xxxx }
    Occurence #8    { xxxx, xxxx }

此外,这根本不是正则表达式,而且这些模式非常粗糙。如果您需要真正的正则表达式,请查看此处。

最新更新