I’m writing a macro to find matches using a regex pattern. For each match I would like to replace it with a substring from the match itself.
For example:
Find all strings with the pattern “#vl-.*vl#”
It is supposed to get me a string such as “#vl-1 123vl#.
I want to replace the entire string with the substring “vl-1” from the match.
What i got so far is as follows:
Sub RegexReplace()
Dim objRegExp As regExp
Dim ObjMatch As Match
Dim colMatches As MatchCollection
Dim RetStr As String
Set objRegExp = New regExp
objRegExp.Pattern = “vl-.*vl#”
objRegExp.IgnoreCase = True
objRegExp.Global = False
Selection.WholeStory
Dim str As String
str = Selection.text
Dim result As String
If (objRegExp.Test(str) = True) Then
Set colMatches = objRegExp.Execute(str) ‘Execute Search
For Each ObjMatch In colMatches ‘ Iterate matches collection
RetStr = RetStr & ObjMatch.Value & vbCrLf
Next
Else
End IF
TestRegExp = RetStr
End Sub
In case i have more than one match, I’ll get a single string containing all matches.
Couldn’t realize how I manipulate the match as a String.
And also how to replace the existing match before going to the next one.
I’m new in VBA...
question from:
https://stackoverflow.com/questions/65944768/how-can-i-find-using-regex-in-word-vba-and-replace-each-match-with-a-substring-f 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…