In Excel VBA, how to replace all sub-strings of xyz(*)in a string which contains several instances of this sub-string?
* in xyz(*) means every thing in between the two parenthesis. For example the string is "COVID-19 xyz(aaa) affects xyz(bbbbbb) so much families." This changes to "COVID-19 affects so much families."
-
Would help to show an actual example.Tim Williams– Tim Williams2020-03-29 06:53:51 +00:00Commented Mar 29, 2020 at 6:53
-
google.com/search?q=vba+regex+replace+site:stackoverflow.com in particular this one: stackoverflow.com/questions/22542834/…Tim Williams– Tim Williams2020-03-29 06:55:11 +00:00Commented Mar 29, 2020 at 6:55
Add a comment
|
2 Answers
You should use a regular expression.
for example:
Sub a()
Dim Regex As New RegExp
Dim SubjectString As String
SubjectString = "COVID-19 xyz(test) affects xyz(test) so much, families."
With Regex
.Global = True
.Pattern = "(\sxyz(\S*))"
End With
Dim ResultString As String
ResultString = Regex.Replace(SubjectString, "")
MsgBox (ResultString)
End Sub
the first \s used to grab 1 whitespace before the xyz, so when you delete replace, it won't leave 2 white spaces. <br> then looking for the string xyz and the opening parenthesis, inside it I look for \S which is any char and * means 0 or more times and then I look for the closing parenthesis.
5 Comments
dahan raz
Sorry, I didn't pay attention it was excel VBA, my bad.can you check my update please?
Fighter Jet
@dahanraz It just replaced the first occurrence of the xyz(test)! Please fix this issue and could you explain more how the regEx works?
dahan raz
@FighterJet fixed just add the flag .Global=True to the regex var. simple explanation to regex its some kind a pattern "language" that you can use to build your patterns and then find matches to the patterns. also make sure to mark my answer as correct if its what you asked for.
Fighter Jet
@dahanraz What are the beginning and ending parentheses used for?
QHarr
update seems fine :-) + You might wish to include the appropriate lib reference as is early bound. Up to you.
here's a solution avoiding regexp, which I tend to avoid whenever possible and convenient (as this case seems to me)
Dim s As String
s = "COVID-19 xyz(aaa) affects xyz(bbbbbb) so much families."
Dim v As Variant
For Each v In Filter(Split(s, " "), "xyz(")
s = Replace(s, v & " ", vbNullString)
Next
I got the use of Filter() from this post