在VBA中使用Regex隐藏Word中的匹配项



一段时间以来,我一直在VBA中使用Regex,我已经能够在Regex中找到不同的值或替换它们,或者寻找子字符串并替换它们。然而,我想做的是隐藏特定的值,类似于Word的本地查找和替换。是否有任何转机与正则表达式做到这一点?

Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
Selection.Find.Replacement.Font.Hidden = True
Selection.Find.Replacement.Highlight = False
With Selection.Find
    .Text = "<*>"
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindAsk
    .Format = True
    .MatchCase = False
    .MatchWholeWord = False
    .MatchKashida = False
    .MatchDiacritics = False
    .MatchAlefHamza = False
    .MatchControl = False
    .MatchByte = False
    .MatchAllWordForms = False
    .MatchSoundsLike = False
    .MatchFuzzy = False
    .MatchWildcards = True
End With
Selection.Find.Execute Replace:=wdReplaceAll

我想用正则表达式来做这个。例如:

regEx.Pattern = ([[^[]*?]|<[^<]*?>|^http.*?$)
regEx.Global = True
If regEx.Test(strSource) Then
    Set matches = regEx.Execute(strSource)
    Selection.Text=matches                            
    Selection.Font.Hidden = True
End If

这个想法是将匹配的值分配给选定的文本,但不会丢失所有其余的内容,以便能够隐藏与正则表达式匹配的值。

谢谢你,

我认为最简单(虽然可能不是最有效)的方法是将这两种方法结合起来

    Dim rng As Range
    Dim mtch as Object
    Set rng = ActiveDocument.Range 'or whatever
    'set regex values and execute
    With regEx
        'your options here
        .pattern = strPattern
        Set matches = .Execute(rng.Text)
    End With
    'hide matches
    For Each mtch In matches
        With rng.Find
            'your options here
            .Text = mtch.Value
            .Replacement.Font.Hidden = True
            .Execute Replace:=wdReplaceAll
        End With
    Next mtch

如果你有很多重复的匹配,这将做很多不必要的搜索,所以你必须找到一种方法来消除重复的(像字典)。

最新更新