在vbscript中的匹配字符串后面读取文本

时间:2014-05-29 08:11:28

标签: vbscript cmd

我正在从命令提示输出中读取值,并在excel中输入从命令提示符读取的值。有没有办法读取匹配字符串后面的值。 例如,在ping中,

Pinging 10.140.79.20 with 32 bytes of data:
Reply from 10.140.79.20: bytes=32 time<1ms TTL=255
Reply from 10.140.79.20: bytes=32 time<1ms TTL=255
Reply from 10.140.79.20: bytes=32 time=1ms TTL=255
Reply from 10.140.79.20: bytes=32 time<1ms TTL=255

在上面的ping输出中,有没有办法通过使用vbscript读取“TTL =”字符串后的值来读取TTL值?

2 个答案:

答案 0 :(得分:0)

有许多方法可以从字符串中剪切部分。在你的情况下,在“=”上使用Split()似乎是一个简单的策略:

>> s = "Reply from 10.140.79.20: bytes=32 time<1ms TTL=255"
>> t = CInt(Split(s, "=")(2))
>> WScript.Echo TypeName(t), t
>>
Integer 255
>>

如果您需要输出线的更多部分,RegExp会让您获得更多优势:

>> Set r = New RegExp
>> r.Global = True
>> r.Pattern = "\d+"
>> Set ms = r.Execute(s)
>> WScript.Echo ms(0).Value, ms(4).Value, ms(6).Value
>>
10 32 255
>>

更新斯特凡的评论:

德勤。对于某些(特殊)情况,仍然可以使用Split()方法:

>> s = "Reply from 10.140.79.20: bytes=32 time=1ms TTL=255"
>> a = Split(s, "=")
>> t = CInt(a(UBound(a)))
>> WScript.Echo TypeName(t), t
>>
Integer 255

然后看起来好像没有足够的降压。

答案 1 :(得分:0)

您只需搜索TTL即可。然后读取4个字符,直到行尾。

intPos = InStrRev(s, "TTL", -1, vbTextCompare)

If intPos > 0 Then
    WScript.Echo Mid(s, intPos + Len("TTL="))
End If

如果您的输出看起来像initial time: 5.00003ms , final time: 5.99044ms,请在上面的代码中将"TTL"替换为"final time:"

您还可以在 "final time:"上拆分,在这种情况下,第二个数组元素将是您需要的。

' Split and return what comes after 'final time:' in one step...
strTime = Split(s, "final time:", -1, vbTextCompare)(1)