如何将键值对的字符串字符串转换为数组

时间:2015-11-07 13:58:14

标签: vbscript split key-value

我有以下样本数据。我想将此字符串转换为数组

device_name="Text Data" d_id=7454579598 status="Active" Key=947-4378-43248274

我试过以下:

Const ForReading = 1 

Set objFSO = CreateObject("Scripting.FileSystemObject") 
Set objTextFile = objFSO.OpenTextFile _ 
    ("d:\vbfile.txt", ForReading) 

Do Until objTextFile.AtEndOfStream 
    strNextLine = objTextFile.Readline 
    arrServiceList = Split(strNextLine , " ") 

    For i = 0 to Ubound(arrServiceList) 
        Wscript.Echo  arrServiceList(i) 
    Next 
Loop 

它生成在

之下
device_name="Text
Data"
d_id=7454579598
status="Active"
Key=947-4378-43248274

预期输出

device_name="Text Data"    
d_id=7454579598
status="Active"
Key=947-4378-43248274

2 个答案:

答案 0 :(得分:3)

这种方法怎么样:

Option Explicit

Const ForReading = 1
Dim FSO, keyValueExpr
Set FSO = CreateObject("Scripting.FileSystemObject") 

Set keyValueExpr = New RegExp
keyValueExpr.Pattern = "\b(\w+)=(""[^""]*""|\S*)"
keyValueExpr.Global = True

Dim result, record, match
Set result = CreateObject("Scripting.Dictionary")

With FSO.OpenTextFile("D:\vbfile.txt", ForReading)
    While Not .AtEndOfStream
        Set record = CreateObject("Scripting.Dictionary")
        result.Add result.Count + 1, record
        For Each match In keyValueExpr.Execute(.ReadLine)
            record.Add match.SubMatches(0), match.SubMatches(1)
        Next
    Wend
    .Close
End With

Dim msg, lineNo, key
For Each lineNo In result
    msg = "Line " & lineNo & vbNewLine
    For Each key In result(lineNo)
        msg = msg & vbNewLine & key & ": " & result(lineNo)(key)
    Next
    MsgBox msg
Next

它使用正则表达式来识别满足以下条件的键值对:

  • 键是一串字符(a-z),数字(0-9)或下划线(_)
  • 该值是用双引号括起来的任何内容或除空格外的任何内容。
  • 比较https://regex101.com/r/zL2mX5/1

该程序创建嵌套字典,外部字典包含文件的所有行以及键的相应行号(1..n),每个内部字典保存在每行上找到的键值对。

这种布局让您有机会非常方便地解决每个价值:

value = result(3)("status")

答案 1 :(得分:2)

这是一个可能有用的功能。它需要一个字符串和一个分隔符,并返回一个通过拆分分隔符获得的数组 - 只要分隔符不在引号内:

Function SmartSplit(s, d)
    Dim c, i, j, k, n, A, quoted
    n = Len(s)
    ReDim A(n - 1)
    quoted = False
    i = 1
    k = 0
    For j = 1 To n
        c = Mid(s, j, 1)
        If c = """" Then quoted = Not quoted
        If c = d And Not quoted Then
            A(k) = Mid(s, i, j - i)
            k = k + 1
            i = j + 1
        End If
    Next
    If i < n Then
        A(k) = Mid(s, i)
    Else
        k = k - 1
    End If
    ReDim Preserve A(k)
    SmartSplit = A
End Function

在您的示例中 - 只需将Split替换为SmartSplit即可。