Thread: [Solved] Capture group in RegEx
View Single Post
 
Old 01-02-2021, 05:47 AM
alex100 alex100 is offline Windows 7 64bit Office 2016
Advanced Beginner
 
Join Date: May 2020
Posts: 79
alex100 is on a distinguished road
Default Capture group in RegEx

I am using the code below to find and replace some text. I uses a RegEx that has two groups "(.*?)".

Code:
Dim objRegex As regExp
Dim matches As MatchCollection
Dim fnd As Match
Set objRegex = New regExp
With objRegex
    .Pattern = "\[\|\]" & vbCr & "(.*?)" & vbCr & "(.*?)" & "\|" & vbCr
    .Global = True
    .IgnoreCase = True
    Set matches = .Execute(Selection.Text)
End With
With Selection
    .HomeKey wdStory
    With .Find
        .ClearFormatting
        .Forward = True
        .Format = False
        .MatchCase = True
        For Each fnd In matches
            .Text = fnd
            .Execute
            If .Found = True Then
                Selection.TypeText Text:="-------------"
            End If
        Next fnd
    End With
 End With
The RegEx works good.

I do have a problem though... how can I capture the first group in the RegEx and add it before the replacement text (which is this line: "-------------")?

Currently, the replacement text is added using the 'Selection.TypeText' instruction, as you can see. That's because I couldn't find the way to use the '.Replacement.Text' instruction for this particular code. I tried using it, but nothing seemed to work.

Anyhow, I guess the solution could be something like this:

.Replacement.Text="$1-------------"

where $1 represents the first captured group in the RegEx. This is just an example that should help you better understand what I'm looking for.

Alex
Reply With Quote