vbsn00b
vbsn00b

Reputation: 1

VBScript RegEx Pattern Match using existing String

Good morning,

I'm new to VBScript and not great with RegEx just yet. I'm working on a project in which I need to match a pre-existing string to the beginning of a line in a text file, then place that whole line into a string. In my test, I can assign my own string, but in the production environment, it will pull the string from an object int he application. For example, the string would be "0001", and the beginning of the line in the text file would be 0001, followed by the rest of the text that I also need to apply to the new string. Below is the code that I have so far. My issue is that I don't know how to apply the current string to the RegEx pattern, or what else I would need to include in it to perform exactly this search.

Dim strCode
strCode = "0001"

Dim objFSO, objFile, objRegEx
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objRegEx = CreateObject("VBScript.RegExp")
objRegEx.Pattern = strCode & 'This is where I'm not sure exactly how to apply RegEx

Dim afterMid
Dim n
n = 4

Dim result
Dim newString
Dim LogFile
LogFile = "c:\Users\runto\Documents\Test Logfile.txt"
Set objFile = objFSO.OpenTextFile(LogFile,1)

Do Until objFile.AtEndOfStream
    strSearchString = objFile.ReadLine
    Set colMatches = objRegEx.Execute(strSearchString)
    If colMatches.Count > 0 Then
    For Each strCode in colMatches
        newString = strSearchString
    Next
    End If
Loop

MsgBox newString

Any help would be massively appreciated. Thanks!

Upvotes: 0

Views: 5536

Answers (1)

Gary_W
Gary_W

Reputation: 10360

Match line starting with strCode:

objRegEx.Pattern = "^" & strCode & ".*"

'^'     = Anchor to the start of the string
strCode = followed by your pattern
'.'     = followed by any character
'*'     = followed by zero or more occurrences of the previous character

So the regex becomes "^0001.*"

Oh and you can use

objRegEx.Test(strSearchString)

To see if the string matches your pattern.

Update: Test script illustrates how to first escape non-alphanumeric characters, then performs the comparison:

Dim strCode
Dim strSearchStr
strCode = "0.0[1"
strSearchString = "0.0[1 - test string"

Set objRegEx = CreateObject("VBScript.RegExp")
objRegEx.Pattern = "([^A-Za-z0-9])"   ' Match non-alphanum chars
objRegEx.global = True
strCode = objRegEx.replace(strCode, "\$1")  ' Escape with a backslash
'msgbox strCode
objRegEx.Pattern = "^" & strCode & ".*"     ' Compare like before
if objRegEx.Test(strSearchString) then
  msgbox "match"
else
  msgbox "No match"
end if

Upvotes: 2

Related Questions