VBS Regex getting the underscore from a string

Viewed 195

I have a simple outcome to detect part of a file name. My files have their general name (FILENAME), a second name (SECONDNAME#) and a final tag, all links by underscores.

I am after the second name, which can have a small number of values. The third part, the final tag, can be highly variable and is not checked for.

FILENAME_SECONDNAME1_DS.txt

FILENAME_SECONDNAME2_DS.txt

FILENAME_SECONDNAME3_ER.txt

Detecting the trailing underscore after teh second name is important to help indicate I have the second name and are not accidentally detecting a similar string part in the filename.

I check with the following

set RE = new RegExp
RE.Ignorecase = true

sCONST = "FILENAME_SECONDNAME1_DS.txt"

RE.pattern = "(SECONDNAME1)|(SECONDNAME2)|(SECONDNAME3)_"
if RE.test(sCONST) = true then
    set matches = RE.Execute(sCONST)
    for each match in matches
        MsgBox match.Value
    next
end if

VB's RegExp matches my pattern but match.Value never has the underscore. I can only assume I am not matching the underscore with my pattern. How can I get the underscore included in my matches?

2 Answers

The pipe works on the whole thing, so with your current regex, the 3 possible alternatives are SECONDNAME1, SECONDNAME2, and SECONDNAME3_.

That being said, you don't even need the pipe operator in this case.

Do the following instead:

SECONDNAME[1-3]_

Just match SECONDNAME followed by either 1, 2, or 3, which is then followed by an underscore.

Demo

You can build your pattern into groups in order to gain access them easily after :

Demo here ^(\w+_)(\w+_)(.*)(\.txt)$

Set RE = new RegExp
RE.Ignorecase = True
RE.global = True
RE.MultiLine = True
RE.pattern = "^(\w+_)(\w+_)(.*)(\.txt)$"

sCONST = "FILENAME_SECONDNAME1_DS.txt" & vbCrlf &_
"FILENAME_SECONDNAME2_DS.txt" & vbCrlf &_
"FILENAME_SECONDNAME3_DS.txt" & vbCrlf &_
"FILENAME_SECONDNAME4_DS.txt" & vbCrlf &_
"FILENAME_SECONDNAME5_ER.txt" & vbCrlf &_
"FILENAME_SECONDNAME6_ER.txt"

If RE.test(sCONST) = True then
    Set matches = RE.Execute(sCONST)
    For Each match in matches
        MsgBox "The first group is : "& match.subMatches(0) & vbCrlf & _
        "The second group is : "& match.subMatches(1) & vbCrlf & _
        "The third group is : "& match.subMatches(2) & vbCrlf & _
        "The fourth group is : "& match.subMatches(3)
    Next
End if
Related