我有以下示例数据。我想把这个字符串转换成数组
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)或下划线(_)
- 该值是用双引号括起来的任何内容或除空格之外的任何内容。
- 比较 https://regex101.com/r/zL2mX5/1
该程序创建嵌套字典,外部字典保存文件的所有行以及相应的行号(1..n)作为键,每个内部字典保存每行上找到的键值对。
这种布局使您有机会非常方便地处理每个值:
value = result(3)("status")
关于vbscript - 如何将键值对的字符串转换为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33583545/