vbams-word

Difference in regular expressions in Find_and_Replace and RegExp


I need to find and replace text consisting of the characters: * one character, - one character, one or more digits, - one character, one or more letters, _ one or more characters.

In RegExp I successfully use the pattern "*{1}-{1}\d{1,}-{1}[A-Z]{1,}_{1,}" to find the first match (this is necessary in my code), then I try to apply the same pattern in the Find_and_Replace method and nothing changes.

It's code work:

    Set regEx = New RegExp
    regEx.IgnoreCase = False
    regEx.MultiLine = True
    regEx.Global = False
    regEx.Pattern = "\*{1}\-{1}\d{1,}\-{1}[A-Z]{1,}\_{1,}"

    If regEx.Test(Rng) Then
        Set Matches = regEx.Execute(Rng)
        MsgBox Matches(0).FirstIndex + 1
    Else
        MsgBox 0
    End If

This code don't work:

    With Rng.Find
        .ClearFormatting
        .Text = "\*{1}\-{1}\d{1,}\-{1}[A-Z]{1,}\_{1,}"
        .Wrap = wdFindContinue
        .MatchWildcards = True
        With .Replacement
            .ClearFormatting
            .Font.Bold = True
            .Font.Underline = True
            
            .Text = "Bla-bla-bla"

        End With
        
        .Execute
    
        If .Found = True Then
            .Execute Replace:=wdReplaceOne
        End If
   end with

Solution

  • .Text = "\*-[0-9]@-[A-Z]@_{1,}"
    

    or, if you're not using English-language regional settings:

    .Text = "\*-[0-9]@-[A-Z]@_{1;}"
    

    The above will find content like:

    *-1-A_

    *-12-A_

    *-1-AB_

    *-12-AB__

    and so on.