Created
September 20, 2017 10:18
-
-
Save neblish/b328bc373669d13bec5b3f04ec02d2a3 to your computer and use it in GitHub Desktop.
MS Excel - VBA function to extract text using Regex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
' Shamelessly leeched from StackOverflow: https://stackoverflow.com/questions/7086270/how-to-extract-text-within-a-string-of-text | |
Function RegexExtract(ByVal text As String, _ | |
ByVal extract_what As String, _ | |
Optional separator As String = ", ") As String | |
Dim allMatches As Object | |
Dim RE As Object | |
Set RE = CreateObject("vbscript.regexp") | |
Dim i As Long, j As Long | |
Dim result As String | |
RE.pattern = extract_what | |
RE.Global = True | |
Set allMatches = RE.Execute(text) | |
For i = 0 To allMatches.count - 1 | |
For j = 0 To allMatches.Item(i).submatches.count - 1 | |
result = result & (separator & allMatches.Item(i).submatches.Item(j)) | |
Next | |
Next | |
If Len(result) <> 0 Then | |
result = Right$(result, Len(result) - Len(separator)) | |
End If | |
RegexExtract = result | |
End Function |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment