Reputation: 9546
I have a string starting with some asterisk-bounded substrings, e.g.,
*AB**XY**DZ*There is more text
I want to get an array of all these substrings; in this case the array would be as follows:
[1] AB
[2] XY
[3] DZ
The following strings should not return any matches:
There is *AB**XY**DZ* more text
There is more text *AB**XY**DZ*
I've implemented this by capturing the whole asterisk-bounded group at the beginning with regex, then processing that result to get the substrings, as follows:
Public Function getCodeArray(commentString As String) As Variant
Dim codeString As String
Dim mCol As MatchCollection
Dim regex As RegExp
Dim delimiter As String
Set regex = New RegExp
regex.Pattern = "^([*][A-Za-z]{2}[*])+"
delimiter = "|"
Set mCol = regex.Execute(commentString)
codeString = mCol(0).Value
codeString = Replace(codeString, "**", delimiter)
codeString = Replace("*", "")
getCodeArray = Split(codeString, delimiter)
End Function
Is there a way that I can set up the regex so that I can directly return the 2-letter substrings as mCol
's matches and not have to use replace()
and split()
?
Upvotes: 0
Views: 506
Reputation: 22876
Simplest is to Split by "*"
and get the odd elements of the result:
s = "There is *AB**XY**DZ* more text"
a = Split(s, "*")
For i = 1 To UBound(a) Step 2
Debug.Print a(i)
Next
Other options can be to experiment with negative and positive lookahead https://regex101.com/r/ZbEb4U/1
or match the *
s too https://regex101.com/r/ZbEb4U/2
Upvotes: 2