AI – VBScript – Finding Indexes – Pattern Recognition

email me

The following VBScript finds all occurrences of a word, or a pattern using a regular expression. A regular expression specifies what kind of pattern to match, and can be any string of characters and/or numbers. In my example, “\w+” will look for one word at a time using spaces (whitespace, specifically). The whitespace acts as a delimiter between words, thus…I can determine how many words there are, and where each word begins, which is commonly called an index. An index value can be useful in managing elements in arrays and lists.

But, more importantly, I could easily search for a specific word or words, a pattern of special characters, or even more complex text, like programming code in a web page. Based upon what is being scanned and returned by the regular expression, I could then perform a function on the data.  It’s very powerful, to say the least.

 

The Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
Option Explicit

Dim txtSource, thePattern, objMatchPattern, Match, Matches, count

txtSource = "The man in the moon is very far away"
thePattern = "\w+" ' you can change this part
count = 0

'Create the regular expression.
Set objMatchPattern = New RegExp
objMatchPattern.Pattern = thePattern
objMatchPattern.IgnoreCase = False
objMatchPattern.Global = True

'Perform the search.
Set Matches = objMatchPattern.Execute(txtSource)

'Iterate through the Matches collection.
For Each Match in Matches
   msgbox Match.FirstIndex & " " & Match.Value
   count = count + 1
Next

msgbox "total count: " & count


'clear session
set txtSource = Nothing
set thePattern = Nothing
set objMatchPattern = Nothing
set Match = Nothing
set Matches = Nothing

'The Index and Word Output:
' 0 The
' 4 man
' 8 in
' 11 the
' 15 moon
' 20 is
' 23 very
' 28 far
' 32 away
' total count: 9

 

 

Notes

https://www.tutorialspoint.com/vbscript/vbscript_reg_expressions.htm