• Matching URLs with wildcards (any)

    Author
    Topic
    #409092

    I often need to do stuff to URLs in text, and matching them with wildcards can be tricky. A major obstacle was that I needed to format the URL, but not the boundary characters I used to find it (spaces, parens, etc.). So I ended up having to do a bit of range gymnastics.

    The following macro does a fair job of getting most standard URL formats. Feel free to offer suggestions or to adapt for your own purposes.

    Sub MatchURLs()
    ' 
    ' Matches most www, ftp, and http(s) variations.
    ' Known issues: doesn't currently seem to match 
    '  if URL is at end of table cell
    '
    Dim rngToSearch As Range
    Dim rngURL As Range
    
    Set rngToSearch = ActiveDocument.Range
    Set rngURL = rngToSearch.Duplicate
    
    Do
        With rngURL.Find
            .ClearFormatting
            .Text = " [htps:/wf.]{3,5}[! ,)(^013^019]@[ ,)(^013^019]"
            .Forward = True
            .MatchWildcards = True
            .Wrap = wdFindStop
            .Execute
        End With
        
        If rngURL.Find.Found = False Then
            Exit Do
        End If
        rngURL.MoveEnd unit:=wdCharacter, Count:=-1
        rngURL.MoveStart unit:=wdCharacter, Count:=1
        '
        ' ######################
        ' Do stuff to rngURL Here
        '
        ' ######################
        '
        rngURL.MoveStart wdWord
        rngURL.End = rngToSearch.End
    Loop Until rngURL.Find.Found = False
    
    End Sub
    

    Cheers!

    Reply To: Matching URLs with wildcards (any)

    You can use BBCodes to format your content.
    Your account can't use all available BBCodes, they will be stripped before saving.

    Your information: