2017-06-13 195 views
0

我创建了一个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}那样有空格的字符串。

EX:这是一个例子{xxxx} --getting processed.this是[fieldcode]。这是没有得到处理的字符串{xxx}。

回答

0

您需要在OCCURENCES 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 } 

而且,这不是一个正则表达式都和传统的图案非常粗糙。如果你需要一个真正的正则表达式,看看here

+0

嗨,谢谢你的帮助......但在文本中,我们有一个字段代码之间所需的字符串......一旦找到字段代码,它不会读取下一个发生。 例如: 所有文本为: {xxxxx} [field code] asdasd {xxxx} As {asd} asff {xxx} {xxxx,xxxx} safasf {xxxx,xxxx} {xxxx,xxxx} {xxxx,xxxx } 在这种情况下,它只会读取第一个事件。我已尝试提供的解决方案,并提供以下输出: 发生: 发生#1 {xxxxx} 发生#2 发生#3 \t。 \t。 \t。 \t。 \t无限 – Rocky

+0

@Rocky,它适用于我的“全部文本”。我[有9次出现](https://i.stack.imgur.com/2XyIO.png)(你的域代码也被捕获了),所以我认为这是你的愿望,不是吗?不幸的是,我不熟悉这些模式。 – CommonSense

+0

@Rocky,我也建议你放弃那些丑陋的模式,并使用RegEx代替!像regex101.com这样的网站很多,您可以在网上粘贴更多的数据和测试模式。我敢肯定,规则模式“抓住所有花括号内的花括号,如果之后有方括号 - 如果我理解你的规则,就可以用同样的方式抓住它们”更容易,更可读。所以试试真实的数据,如果你再次卡住 - 更新你的问题链接到regex101。干杯! – CommonSense