Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
308 views
in Technique[技术] by (71.8m points)

How can i find using regex in word VBA and replace each match with a substring from the match?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just use replace and submatch.

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
        testregexp = objRegExp.Replace(str, "$1")
       '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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...