简体   繁体   中英

Hide matches in a Word using Regex in VBA

For a while I've been working with Regex in VBA, and I've been able to find the different values in the regex or replace them, or looking for substrings and replace them. However, what I would like is to hide the specific values doing something similar to the native find and replace of Word. Is there any turnaround with regex to do this?

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

And I would like to do this with a regex. For example like that:

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

The idea is assign to the selected text the values of the matches, but without losing all the rest of the content, to be able to hide the values that match with the regex.

Thank you,

I think the easiest (though maybe not most efficient) way would be to combine the two methods

    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

If you have many duplicate matches this will do a lot of unnecessary searches so you'd have to find a way to eliminate the duplicates (like a dictionary).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM