Batman1,
Very interesting. After studying your last (which works perfectly), I thought I would modify slightly just to confirm my understanding. The result is a little simpler for me to understand and will provide notes for myself should I ever need to revisit.
Thanks again for your lessons in RegEx:
Code:
Sub RegExPsuedoLookBack()
Dim RegEx As Object, Matches As Object, Match As Object
Dim oRng As Range
'Sample document text: Jack Sprat, Johnny Sprat, Tom Sprat, Mary Sprat and Bill Sprat.
'With RegEx look ahead, you can find all instances of x = "Sprat" preceded by either y = "Jack " or y = "Tom "
Set RegEx = CreateObject("VBScript.RegExp")
With RegEx
.Global = True
.Pattern = "(?=Tom|Jack)\S+ Sprat"
End With
Set Matches = RegEx.Execute(ActiveDocument.Range.Text)
For Each Match In Matches
'Returns all instances of "Sprat" immediately after "Tom " or "Jack ".
Debug.Print Match.Value 'Notice the match return includes the proceeding y qualifyer.
Next
'A RegEx look back will return all instances of x = "Sprat" preceded by y = "Jack " or y = "Tom " but the match return only inclues the x value "Sprat"
Set RegEx = CreateObject("VBScript.RegExp")
With RegEx
.Global = True
.Pattern = "(?<=Tom |Jack )\Sprat"
End With
On Error GoTo lbl_EH
Set Matches = RegEx.Execute(ActiveDocument.Range.Text)
For Each Match In Matches
'If this worked, it would return all instances of "Sprat" immediately after "Tom " or "Jack ".
Debug.Print Match.Value
Next
lbl_ER:
'VBA workaround for RegEx look back.
With RegEx
.Global = True
'Use a modified look ahead as demonstrated previously.
.Pattern = "((?=Tom|Jack)\S+ )Sprat" 'Note the addition of parens "()" around the y element will result in a submatch.
End With
Set Matches = RegEx.Execute(ActiveDocument.Range.Text)
For Each Match In Matches
'Returns x = "Jack Sprat" and "Tom Sprat" matches at before.
'However, also returns the submatches "Jack " from the "Jack Sprat" match and "Tom " from the "Tom Sprat" match.
'Use these manipulate the returned range to achieve a VBA pseudo lookback method.
ActiveDocument.Range(Match.FirstIndex + Len(Match.Submatches(0)), Match.FirstIndex + Match.Length).HighlightColorIndex = wdBrightGreen
Next
lbl_Exit:
Exit Sub
lbl_EH:
MsgBox "Unfortunatley RegEx look back is not supported in VBA." & vbCr + vbCr _
& "Proceding to work around.", vbInformation + vbOKOnly, "INVALID OPERATION"
Resume lbl_ER
End Sub
Please feel free to further comment, if my notes above could be clarified further.