如何使用正则表达式匹配一个或两个单词

时间:2017-07-30 16:29:53

标签: regex word-vba

我想在以下文字中的部分之后提取评分。它可以是一个字或两个字。例如“Partly Satisfactory”,“Satisfactory”。我应该使用哪种正则表达式模式?我正在使用word vba

Section 1
Partly Satisfactory 
Some paragraphs inserted here

Section 2
Satisfactory
Another paragraphs inserted here

Section 3
Partly Unsuccessful
Another paragraphs inserted here

1 个答案:

答案 0 :(得分:0)

模式可以是例如:(Section \d+[\r\n])(\w+(?: \w+)?)

第一个捕获组捕获第一行( Section ,number和newline)。

第二个捕获组获得评级(一两个字) 这就是你真正需要的。

下面是一个示例脚本,在Word文档上检查(用作宏)。

Sub Re()
  Dim pattern As String: pattern = "(Section \d+[\r\n])(\w+(?: \w+)?)"
  Dim regEx As New RegExp
  Dim src As String
  Dim ret As String
  Dim colMatches As MatchCollection
  Dim objMatch As Match

  ActiveDocument.Range.Select
  src = ActiveDocument.Range.Text
  Selection.StartOf

  With regEx
    .Global = True
    .MultiLine = True
    .pattern = pattern
  End With
  If (regEx.Test(src)) Then
    Set colMatches = regEx.Execute(src)
    ret = "Matches " & colMatches.Count & ": "
    For Each objMatch In colMatches
      ret = ret & vbCrLf & objMatch.SubMatches(1)
    Next
  Else
    ret = "Matching Failed"
  End If
  MsgBox ret, vbOKOnly, "Result"
End Sub