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

How to convert a string string of key-value pairs into an array

我有以下样本数据。我想把这个字符串转换成数组

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

这种方法怎么样:

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)或下划线(_)
  • 该值是用双引号引起来的任何值或除 space.
  • 之外的任何值
  • 比较https://regex101.com/r/zL2mX5/1

程序创建嵌套字典,外部字典包含文件的所有行,并为键提供相应的行号 (1..n),每个内部字典包含在每一行中找到的键值对。

此布局让您有机会非常方便地处理每个值:

value = result(3)("status")

这是一个可能有用的函数。它需要一个字符串和一个分隔符以及 returns 一个通过拆分分隔符获得的数组——只要分隔符不在引号内:

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 即可。