我正在尝试从左边界为test/time (ms)=
且右边界为, test/status=0
的字符串中获取值。
例如,如果我有一个看起来像的输入字符串:
input="test/ing=123, hello/world=321, test/time (ms)=100, test/status=0"
在Perl中,我知道我可以做类似的事情:
input=~/"test/time (ms)="(.*)", test/status=0"/;
$time=$1;
$time
将保留我想要获得的价值。
不幸的是,我只能在Windows Batch或VBScript中编写代码。有谁知道批处理如何执行与Perl中的操作相同的操作?
答案 0 :(得分:2)
纯批次:
for /f "delims==," %%A in ("%input:*test/time (ms)=%) do echo %%A
IN子句中的搜索和替换查找test/time (ms)
的第一次出现,并从原始字符串的开头替换为搜索字符串的末尾,没有任何内容。 FOR / F然后使用=
和,
的分隔符解析出100个。
%input%
值中包含引号的存在会导致IN()子句看起来很奇怪而没有可见的结束引号。
延迟扩展看起来更好:
setlocal enableDelayedExpansion
for /f "delims==," %%A in ("!input:*test/time (ms)=!") do echo %%A
我更喜欢将变量值中的引号括起来,并根据需要将它们显式添加到我的代码中。这使得正常的扩展版本看起来更自然(延迟扩展版本保持不变):
set "input=test/ing=123, hello/world=321, test/time (ms)=100, test/status=0"
for /f "delims==," %%A in ("%input:*test/time (ms)=%") do echo %%A
借助JScript批量
如果你有我的hybrid JScript/batch REPL.BAT utility,那么你可以使用正则表达式在解析中非常具体:
call repl ".*test/time \(ms\)=(.*?),.*" $1 sa input
获取变量中的值:
set "val="
for /f "delims=" %%A in ('repl ".*test/time \(ms\)=(.*?),.*" $1 sa input') do set "val=%%A"
请注意,IN()子句中不需要CALL。使用管道时也不需要它。
答案 1 :(得分:1)
的VBScript /正则表达式:
>> input="test/ing=123, hello/world=321, test/time (ms)=100, test/status=0"
>> set r = New RegExp
>> r.Pattern = "\(ms\)=(\d+),"
>> WScript.Echo r.Execute(input)(0).Submatches(0)
>>
100
答案 2 :(得分:1)
批处理文件:
SET input="test/ing=123, hello/world=321, test/time (ms)=100, test/status=0"
FOR %%i IN (%input:, =" "%) DO FOR /F "TOKENS=1,* DELIMS==" %%j IN (%%i) DO IF "%%j" == "test/time (ms)" ECHO %%k
编辑:解释
%input:, =" "%
返回"test/ing=123" "hello/world=321" "test/time (ms)=100" "test/status=0"
外FOR
会将%%i
分配给之前结果中的每个字符串。
内部FOR
会将=
左侧的字符分配给%%j
,将右侧字符分配给%%k
。
然后只是将%%j
与所需的键进行比较,并在匹配时显示值。