Thread: [Solved] Find Challenge
View Single Post
 
Old 01-07-2025, 01:37 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
'Note the addition of parens "()" around the y element will result in a submatch.
This is Backreferences.

With Backreferences:
1. You can use submatch
2. You can refer to an earlier group later in the Pattern ()
3. You can use submatch in REPLACE

Note 1.
You already use it in your code.

Note 2.
Pattern = "([A-Za-z]+) \1"

Pattern = <series1><space><series2>, where <series1> and <series2> are identical

E.g. Pattern = "([A-Za-z]+) \1" will find "a a", "John John". If .IgnoreCase = True then it will also find "A a"

a Pattern = "([A-Za-z]+) ([A-Za-z]+) \2 \1" will find "Jack Sprat Sprat Jack

Note 3.

In Repace we don't use \1, \2, … We use $1, $2, …
Code:
Sub test2()
Dim RegEx As Object, Matches As Object, Match As Object, text As String
    text = "Fellow John John is a good student. Fellow Jack Jack also"
    
    Debug.Print text
    
    Set RegEx = CreateObject("VBScript.RegExp")
    With RegEx
        .Global = True
        .Pattern = "([A-Za-z]+) \1"
        If .test(text) Then
            text = .Replace(text, "$1") ' in every place in string Text where a result is found, that result is replaced with its $1
            
            Debug.Print text
            
        End If
    End With
    
    text = "John Smith is a good student. Jack Sprat also"
    With RegEx
        .Global = True
        .Pattern = "([A-Z][a-z]+) ([A-Z][a-z]+)"
        If .test(text) Then
            text = .Replace(text, "$2 $1")
            
            Debug.Print text
            
        End If
    End With
End Sub
Reply With Quote