Home » excel » vba – multipoint regular expressions match with less for loops and less class re-initialization. optimization

vba – multipoint regular expressions match with less for loops and less class re-initialization. optimization

Posted by: admin May 14, 2020 Leave a comment

Questions:

Is there a way to do multiple regular expressions matches in vba without instantiating multiple instances of the regexp object? For example I want to do several points of regular expression matching between several different fields of data.

For illustrative purposes consider this.

 
column 1       column 2         column 3

AAATDD         Airplane         Transportation/Airplane
BBBTDD         Bus              Transportation/Bus
CCCFDD         Chocolate        Food/Chocolate
DDDFDD         Dog              Food/Potato

So as you can see the first letter in Column 1 is A, which matches the Description in Column 2 for Airplane which matches the type of Transportation (indicated by the T in Column 1 “AAATDD”) in Column 3 for Airplane. All is well. But in Column 1 there is the peculiar entry for Dog which is listed as a Food and Potato.

Right now I have (pseudo) code like this:

for i = 1 to endpoint
    set regexp as new regexp
    regexp.pattern is myPattern
    set colmatches = regexp.execute()

    If Column1_Entry(i) = myMatch.value then
         pass test
    Else
         throw exception
    End if
 next i

but the problem is I can only check the regular expression given by my pattern. For example, my next few lines have to check the SAME values just looking out for a different thing.

When I’m ready to do the next set of matches to determine validity i.e. on Column 3 matching Transportation/”Airplane” to “Airplane” in Column 2 I need to unset regexp and reset myPattern. Is there anyway around this? or a way to maybe store the regularexpressions as a list or array? So they can be looped through in turn? Any help would be greatly appreciated.

How to&Answers:
Dim arr

arr = Array("pattern1","pattern2","pattern3")

set regexp as new regexp

for i = 1 to endpoint     
     for n = lbound(arr) to ubound(arr)
        regexp.pattern = arr(n)
        set colmatches = regexp.execute()      
        If Column1_Entry(i) = myMatch.value then          
           pass test     
        Else          
           throw exception     
        End if  
    next n
next i