Thread: [Solved] Find Challenge
View Single Post
 
Old 01-06-2025, 05:11 PM
batman1 batman1 is offline Windows 11 Office 2013
Advanced Beginner
 
Join Date: Jan 2025
Posts: 57
batman1 is on a distinguished road
Default

Quote:
Originally Posted by gmaxey View Post
Batman1,
No denying that your RegEx code and pattern is simple compared to the Find method. Both your Test() and my ScratchMacroC() return the same results. But, how do you then process the Match object? Let's say that we not only want to Debug.Print the Match.Value, we want to highlight it in the text as well:

Code:
Sub ScratchMacroC()
Dim oRng As Range, oRngProcess As Range
Set oRng = ActiveDocument.Range
Dim lngIndex As Long
  With oRng.Find
    .Text = "[0-9]{1,}"
    .MatchWildcards = True
    While .Execute
      lngIndex = 1
      Set oRngProcess = Nothing
      If InStr(Left(oRng.Text, 4), "2") > 0 Then
        Set oRngProcess = oRng.Duplicate
        Select Case Len(oRng.Text)
          Case Is > 4
            Debug.Print Left(oRng.Text, 5)
            oRngProcess.End = oRngProcess.Start + 5
            lngIndex = 5
          Case Is = 4
            Debug.Print oRng.Text
            oRngProcess.End = oRngProcess.Start + 4
            lngIndex = 4
        End Select
      End If
      oRng.End = oRng.Start + lngIndex
      If Not oRngProcess Is Nothing Then oRngProcess.HighlightColorIndex = wdBrightGreen
    Wend
  End With
lbl_Exit:
  Exit Sub
End Sub

Code:
Sub test()
Dim RegEx As Object, Matches As Object, Match As Object
    Set RegEx = CreateObject("VBScript.RegExp")
    With RegEx
        .Global = True
        .Pattern = "(?=\d{0,3}2)\d{4,5}"
    End With
    Set Matches = RegEx.Execute(ActiveDocument.Range.text)
    For Each Match In Matches
        ActiveDocument.Range(Match.FirstIndex, Match.FirstIndex + Match.Length).HighlightColorIndex = wdBrightGreen
        Debug.Print Match.Value
    Next
End Sub
Quote:
Now, would you mind breaking down your pattern and explaining how it is constructed?

.Pattern = "(?=pattern1)pattern2"
means "find the result of pattern2 whose initial part is pattern1"

It is "zero-width positive lookahead assertion". There is and "zero-width negative lookahead assertion"

1. zero-width positive lookahead assertion
"(?=pattern1)pattern2" - find the result of pattern2 whose initial part is pattern1
pattern2(?=pattern1) - find the result of pattern 2, followed (in further data input) by a string of pattern 1

2. zero-width negative lookahead assertion
(?!pattern1)pattern2 - find the result of pattern 2 whose initial part is not in the form pattern1
pattern2(?!pattern1) - find a result of the form pattern2 after which (in further input data) there is nothing of the form pattern1

Read about zero-width positive lookahead assertion and zero-width negative lookahead assertion on the internet.
Reply With Quote