2017-07-30 46 views
-1

我想在下面的文本段後提取評級。它可以是一個字或兩個字。例如「部分滿意」,「滿意」。我應該使用哪種正則表達式模式?我使用這個詞VBA如何使用正則表達式匹配一個或兩個詞

Section 1 
Partly Satisfactory 
Some paragraphs inserted here 

Section 2 
Satisfactory 
Another paragraphs inserted here 

Section 3 
Partly Unsuccessful 
Another paragraphs inserted here 

回答

0

該模式可爲例如: - (Section \d+[\r\n])(\w+(?: \w+)?)

第一個捕獲組捕獲第一行(部分,數字和換行符)。

第二個捕獲組捕獲評級(一個或兩個詞) ,這就是你的實際需要。

下面你有一個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 
+0

非常感謝!這正是我正在尋找的! –

相關問題