我有以下示例数据。我想将此字符串转换为数组
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
它使用正则表达式来标识满足以下条件的键值对:
该程序创建嵌套字典,外部词典保存文件的所有行,并带有键的相应行号(1..n),每个内部词典保存在每一行上找到的键值对。
这种布局使您有机会非常方便地处理每个值:
value = result(3)("status")
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句