0

I am trying to get a value from a string that has a left boundary of test/time (ms)= and right boundary of , test/status=0.

For example, if I have an input string that looks like:

input="test/ing=123, hello/world=321, test/time (ms)=100, test/status=0"

In Perl, I know I can do something like:

input=~/"test/time (ms)="(.*)", test/status=0"/;
$time=$1;

$time will hold the value that I want to get.

Unfortunately, I can only write the code in Windows Batch or VBScript. Does anyone know how batch can perform the same action as the one in Perl?

Sakura
  • 869
  • 4
  • 13
  • 32

3 Answers3

2

Pure batch:

for /f "delims==," %%A in ("%input:*test/time (ms)=%) do echo %%A

The search and replace within the IN clause looks for the first occurance of test/time (ms) and replaces from the beginning of the original string to the end of the search string with nothing. The FOR /F then parses out the 100 using delimiters of = and ,.

The presence of enclosing quotes within the value of %input% causes the IN() clause to look weird with no visible end quote.

It looks better with delayed expansion:

setlocal enableDelayedExpansion
for /f "delims==," %%A in ("!input:*test/time (ms)=!") do echo %%A

I prefer to keep enclosing quotes out of my variable values, and explicitly add them to my code as needed. This makes the normal expansion version look more natural (delayed expansion version remains same):

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

Batch with help of JScript

If you have my hybrid JScript/batch REPL.BAT utility, then you can use regex to be very specific in your parsing:

call repl ".*test/time \(ms\)=(.*?),.*" $1 sa input

To get the value in a variable:

set "val="
for /f "delims=" %%A in ('repl ".*test/time \(ms\)=(.*?),.*" $1 sa input') do set "val=%%A"

Note that CALL is not needed within IN() clause. It also is not needed when using pipes.

Community
  • 1
  • 1
dbenham
  • 127,446
  • 28
  • 251
  • 390
1

VBScript/RegExp:

>> 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
Ekkehard.Horner
  • 38,498
  • 2
  • 45
  • 96
1

Batch file:

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

EDIT: explanation

%input:, =" "% returns "test/ing=123" "hello/world=321" "test/time (ms)=100" "test/status=0"

Outer FOR will assign %%i to each string from previous result.

Inner FOR will assign characters left of = to %%j, and right ones to %%k.

Then is just comparing %%j with desired key and showing value if match.

LS_ᴅᴇᴠ
  • 10,823
  • 1
  • 23
  • 46