程式設計語言:

程式設計語言:

我在文本中有多個 [word]- [word] 實例,例如 self-interest 而不是 selfinterest,這是正確的形式。我正在嘗試使用 MS Word 的通配符刪除筆畫後的無關空格。在尋找和替換框中我輸入:

尋找:*- *
替換為:\1-\2

然而,這不起作用。完成此任務的正確形式是什麼?

答案1

程式設計語言:

WrapReplace在Word文檔中運作。

Sub WrapReplace()
    Call RegExpReplace("(\w+)\-\s(\w+)", "$1-$2")
End Sub

Private Sub RegExpReplace(pattern As String, Backreference As String)
    Dim strReplacement As String
    Set oRegExp = CreateObject("VBScript.RegExp")

    With oRegExp
        .Global = True
        .IgnoreCase = False
        .pattern = pattern
    End With

    Set matches = oRegExp.Execute(ActiveDocument.Content)
 
    For Each match In matches
        Set matchRange = ActiveDocument.Content
    
        strReplacement = oRegExp.Replace(match.Value, Backreference)
    
        With matchRange.Find
            .Text = match.Value
            .Replacement.Text = strReplacement
        
            .Wrap = wdFindAsk
            .Execute Replace:=wdReplaceOne
        End With
    Next

End Sub

答案2

您忽略了告訴 Word 部分 \1 和 \2 是什麼。在星號連字號和星號周圍加上圓括號,但在星號之間留有空格。在「替換為」中,您不需要連字符,因為它現在被捕獲為 \1 的一部分。

在此輸入影像描述

相關內容