The RegExp object in the Microsoft VBScript Regular Expression type library supports regular expression patterns containing the | (or) operator, which lets you search for multiple substrings at the same time. For example, the following piece of code lets you search for a month name in a source text: |
Click here to copy the following block |
Dim re As New RegExp Dim ma As Match
re.Pattern = "january|february|march|april|may|june|july|september|october|novem" _ & "ber|december"
re.IgnoreCase = True
re.Global = True
For Each ma In re.Execute(sourceText) Print "Found '" & ma.Value & "' at index " & ma.FirstIndex Next |
The code above doesn't search for whole words, though, and would find false matches such as "marches". To force the Execute method to search only for whole words, we must embed the list of words among parenthesis, and add the \b sequence to specify that the occurrence should be on a word boundary: |
Thanks to the Join function, it is easy to create a generic function that searches for any word in an array: |
Click here to copy the following block |
Function InstrAllWords(ByVal Text As String, words() As String, _ Optional IgnoreCase As Boolean) As Variant Dim re As New RegExp Dim ma As Match Dim maCol As MatchCollection Dim index As Long re.pattern = "\b(" & Join(words, "|") & ")\b" re.Global = True re.IgnoreCase = IgnoreCase Set maCol = re.Execute(Text) ReDim res(1, maCol.Count) As Variant For Each ma In maCol index = index + 1 res(0, index) = ma.Value res(1, index) = ma.FirstIndex Next InstrAllWords = res End Function |
Here's is an example of how you can use the function above: |
Click here to copy the following block | Dim words(2) As String words(0) = "Visual": words(1) = "Basic": words(2) = "Windows"
Dim arr() as Variant arr = InstrAllWords(txtSource.Text, words()) For i = 1 To UBound(arr, 2) Print "'" & arr(0, i) & "' at index " & arr(1, i) Next |
|