我正在尝试使用VBA代码分析String。 我读了一个看起来像这样的字符串:
myStringInput = "FRAG_INST = someValue,DR = otherValue, FRAG = anotherValue"
在我的代码中,我想根据字符串中读取的值关联一些变量,我想初始化我的变量:
Dim dr, frag, fraginst As String
fraginst = someValue
dr = otherValue
frag = anotherValue
我尝试过像Trim / Split / InStr组合这样的东西,但我总是错误的值。 我不能只使用“Mid”函数,因为值的长度会从一次执行变为另一次......
为了更清楚,我需要设计这样的功能
fraginst = NiceFunction("FRAG_INST",myStringInput)
它将返回“someValue”
有没有一种简单的方法可以做我想要的事情?
由于
答案 0 :(得分:2)
此解决方案正常运行。也许你可以试试这个。我没有使用任何正则表达式。
<强>方法强> 我首先用分隔符(逗号)分割字符串。遍历每个数组元素并将每个元素拆分为&#39; =&#39;。将值与&#39; =&#39;左侧的字符串进行比较并返回&#39; =&#39;右边的值修剪后。 需要Mid功能。
myStringInput = "FRAG_INST = someValue,DR = otherValue, FRAG = anotherValue"
fraginst = NiceFunction("FRAG_INST",myStringInput)
MsgBox fraginst
Function NiceFunction(str1, str2)
tempArr1 = Split(str2,",")
For i=0 To UBound(tempArr1)
tempArr2 = Split(tempArr1(i),"=")
If StrComp(Trim(tempArr2(0)),str1,1)=0 Then
NiceFunction = Trim(tempArr2(1))
Exit For
End If
Next
End Function
答案 1 :(得分:1)
而不是坚持单身&#39;变量(DR,...)需要在运行时动态创建变量,你应该使用dictionary:
Option Explicit
Function s2d(s)
If IsEmpty(gR) Then
Set gR = New RegExp
gR.Global = True
gR.Pattern = "(\w+)\s?=\s?(\w+)"
End If
Set s2d = CreateObject("Scripting.Dictionary")
Dim m
For Each m In gR.Execute(s)
If s2d.Exists(m.SubMatches(0)) Then
' Error: dup key
Else
s2d.Add m.SubMatches(0), m.SubMatches(1)
End If
Next
End Function
Function qq(s)
qq = """" & s & """"
End Function
Dim gR ' "static" in s2d()
Dim s : s = "FRAG_INST = someValue,DR = otherValue, FRAG = anotherValue"
If 0 < WScript.Arguments.Count Then s = WScript.Arguments(0)
Dim d : Set d = s2d(s)
Dim k
For Each k In d.Keys()
WScript.Echo qq(k), "=>", qq(d(k))
Next
If d.Exists("DR") Then WScript.Echo "DR:", d("DR") ' access 'single' var
输出:
cscript 44282497.vbs
"FRAG_INST" => "someValue"
"DR" => "otherValue"
"FRAG" => "anotherValue"
DR: otherValue
P.S。
我使用了RegExp,因为变量名称必须是&#39; /#39; / match&#34; \ w +&#34;和你的样本数据值dito,而分隔符看起来像一个混乱/创造性地使用空间。有关如何在VBA中使用RegExps的信息,请参阅here。
答案 2 :(得分:1)
Function NiceFunction( varName, inputString )
Dim match
With CreateObject("VBScript.RegExp")
.IgnoreCase = True
.Global = False
.Pattern = "(?:^|,)\s*" & varName & "\s*=\s*([^,]*)"
For Each match in .Execute( inputString )
NiceFunction = match.subMatches.Item(0)
Next
End With
End Function
您可以使用RegExp
对象来提取所需字符串的一部分。