如何使用 VBScript 从该字符串中的静态位置显示字符串的一部分?

How to display a part of string from static position in that string with VBScript?

我有一个使用 VBScript 从数据库中获得的列表(...意味着还有另一个代码)

<%
...
for each x in rs.Fields
Response.Write(x & "<br />")
next
...
%>

我得到了 x 的以下结果:

Eventid=1289,EventActive=True,EventTemplate=13,FeatureEvent=True,EventTitle=BackToSchool,EventCompany=SummerKids
Eventid=981112,EventActive=True,EventTemplate=temp199,FeatureEvent=True,EventTitle=SummerSale 2015,EventCompany=KidsClothesOnSale
Eventid=A20BK913,EventActive=False,EventTemplate=green001,FeatureEvent=False,EventTitle=Example Event Title,EventCompany=TEST
Eventid=MO72221,EventActive=False,EventTemplate=817AA11,FeatureEvent=False,EventTitle=TEST TITLE FOR EVENT,EventCompany=SELF TEST

如何使用 VBScript 在每个 x 中仅显示 EventTitle?

BackToSchool
Summer Sale 2015
Example Event Title
TEST TITLE FOR EVENT

如果您的数据是一致的(总是六个逗号分隔的 key=value 对,您的 key=value 对中不存在逗号,等等),那么您可以只用逗号拆分字符串以获得您的key=value 对,然后在 = 上拆分第 5 个 key=value 对以获得值。

例如:

For Each x In rs.Fields
    kv = Split(x, ",")                   ' Get key=value pairs
    Response.Write Split(kv(4), "=")(1)  ' Output the value of the 5th pair
    Response.Write "<br>"
Next

虽然 this answer by OP 可能适用于特定情况,但它不是很优雅,我更喜欢使用更通用的方法,使用 Dictionary 对象。

方法是:

Function ParseData(rawString, mainDelimeter, subDelimeter)
    Dim oData, x, y
    Dim arrMainParts, arrSubParts
    Dim currentKey, currentValue
    Set oData = CreateObject("Scripting.Dictionary")
    arrMainParts = Split(rawString, mainDelimeter)
    For x=0 To UBound(arrMainParts)
        arrSubParts = Split(arrMainParts(x), subDelimeter)
        If UBound(arrSubParts)>0 Then
            currentKey = arrSubParts(0)
            currentValue = arrSubParts(1)
            If oData.Exists(currentKey) Then
                oData(currentKey) = currentValue
            Else  
                oData.Add currentKey, currentValue
            End If
        End If
        Erase arrSubParts
    Next
    Erase arrMainParts
    Set ParseData = oData
End Function

在这种特定情况下的用法是:

For Each x In rs.Fields
    Set oData = ParseData(x, ",", "=")
    If oData.Exists("EventTitle") Then
        Response.Write(oData("EventTitle") & "<br />")
    End If
    Set oData = Nothing
Next

只是指出一个替代方法,您可以尝试使用 InStr,也...

正如 Bond 所说,您的 CSV 列表是一致的,因此您应该能够使用类似这样的内容进行查找...

(请注意,以下内容取决于您指定的格式,因此如果在逗号或等号之间添加空格,则会出现问题。)

Const cDelim = ","
Const cEqual = "=" 

Function GetItemValueFromList(plist, itemName)
    Dim ip 'Item pointer
    Dim ep 'Equals sign pointer
    Dim pl, ni
    pl = cDelim & plist
    ni = cDelim & itemName & cEqual
    ip = InStr(pl, ni)
    'Just make sure we find something before we try pulling the value...
    If ip > 0 Then
        ep = Instr(ip+1, pl, cEqual)
        GetItemValueFromList = Mid(pl, ep+1, InStr(ep+1, pl, cDelim)-ep-1)
    Else
        GetItemValueFromList = ""
    End If
End Function

感谢 Ekkehard.Horner 指出显而易见的事实 - 我在编写该代码时显然正处于高级阶段。