正则表达式匹配并使用两个分隔词之间的名称

时间:2014-10-30 14:17:14

标签: regex vba ms-word word-vba

我使用此代码保存来自Mailings生成文档的各个文档的每个部分

Sub BreakOnSection()
   ' Used to set criteria for moving through the document by section.
   Application.Browser.Target = wdBrowseSection

   'A mail merge document ends with a section break next page.
   'Subtracting one from the section count stop error message.
   For i = 1 To ((ActiveDocument.Sections.Count) - 1)

'Note: If a document does not end with a section break,
'substitute the following line of code for the one above:
'For I = 1 To ActiveDocument.Sections.Count

      'Select and copy the section text to the clipboard.
      ActiveDocument.Bookmarks("\Section").Range.Copy

      'Create a new document to paste text from clipboard.
      Documents.Add ("C:\Users\simaco\Desktop\New folder (4)\new.dotx")
      Selection.Paste

   ' Removes the break that is copied at the end of the section, if any.
      Selection.MoveUp unit:=wdLine, Count:=1, Extend:=wdExtend
      Selection.Delete unit:=wdCharacter, Count:=1
ChangeFileOpenDirectory "C:\Users\simaco\Desktop\New folder (4)"
      DocNum = DocNum + 1

    With ActiveDocument
    Set r = .GoTo(wdGoToPage, wdGoToLast)
    Set r = .Range(r.Start - 1, .Characters.Count)
    r.Delete
    End With


     ActiveDocument.SaveAs FileName:="test_" & DocNum & ".doc"
     ActiveDocument.Close
      ' Move the selection to the next section in the document.
     Application.Browser.Next
   Next i
   ActiveDocument.Close savechanges:=wdDoNotSaveChanges
End Sub

我希望使用John Doe名称保存每个页面,该名称位于文档中的两个分隔词之间,如下所示:

Employee John Doe that etc etc.

如何使用正则表达式匹配John Doe两个单词(ActiveDocumentEmployee)之间的that,然后才能使用找到的字符串ActiveDocument.SaveAs FileName:="Doc" & FoundString & ".doc"

1 个答案:

答案 0 :(得分:1)

使用此模式

(?<=Employee\s)([a-zA-Z ]+?)(?=\s?that)  

Demo