We help IT Professionals succeed at work.

Regex Help

Delerium1978
Delerium1978 used Ask the Experts™
on
Hi Guys and Gals

Regex question. (I'm terrible at creating them).

I have a directory containing a list of files. I want to test this list to whittle down to relevant files and then find the file with the latest version number.

So for my target goal is finding the latest file version of SCR 416 and the directory contains
these files:

SCR 348 ACCOUNT TYPES DISE IA v0.4.xlsm
SCR 348 ACCOUNT TYPES DISE IA v0.3.xlsm
SCR 348 ACCOUNT TYPES DISE IA v0.2.xlsm
SCR 348 ACCOUNT TYPES DISE IA v0.1.xlsm
SCR 416 Services DISE IA V0.5.xlsm
SCR 416 Services DISE IA V0.4.xlsm
SCR 416 Services DISE IA V0.3.xlsm
SCR 416 Services DISE IA V0.2.xlsm
SCR 416 Services DISE IA V0.1.xlsm
SCR 368 2011 Interworking DISE IA V0.3.xls
SCR 368 2011 Interworking DISE IA V0.2.xls

Open in new window


Thinking the tests should be:

For each file, check to see if the filename has 'SCR 416', 'DISE', 'IA' in it and retreive the number after the last V or v and put in an array and sort the array to get the max value.
... im sure im overcomplicating things.

James
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015
Commented:
See if this suits you:

' Path to the directory containing the files

directory = "EE"

' The required bits you specified. Specify the parts
'  in the order in which they appear in the filename

requiredParts = Array("SCR 416", "DISE", "IA")


' #######################################################
'  You shouldn't need to change anything else past here
' #######################################################

Dim fso
Dim input
Dim searchPattern
Dim maxVersion
Dim maxFilename

maxVersion = -1
maxFilename = "Not Found"
directory = directory & "\"

For Each part In requiredParts
  searchPattern = searchPattern & ".*?" & part
Next

searchPattern = searchPattern & ".*?[vV](\d+\.\d+)"

Set fso = CreateObject("Scripting.FileSystemObject")

For Each file In fso.GetFolder(directory).Files
  With New Regexp
    .Pattern = searchPattern

    Set matches = .Execute(file.Name)
    
    If Not matches Is Nothing Then
      For Each match In matches
        tempVersion = CDbl(match.SubMatches(0))
        
        If tempVersion > maxVersion Then
          maxVersion = tempVersion
          maxFilename = file.Path
        End If
      Next
    End If
  End With
Next

WScript.Echo(maxFilename)

Open in new window

Author

Commented:
Thanks Kaufmed - this did the trick. I added some error handling if the directory didnt exist and it was perfect - just what i needed. Many thanks.

James