2013-09-25 43 views
0

我試圖從左邊界爲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

找到單個'perl.exe'可執行文件(xampp for windows有一個) –

+0

對不起。我不明白你的意思。它如何幫助將腳本更改爲批處理文件格式? – Sakura

+0

使用Perl你不必做任何轉換;) –

回答

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與所需的鍵和顯示值,如果匹配。

+0

嗨,你能解釋一下你的代碼嗎? – Sakura

+0

只是想知道......你是怎麼設置%% k分配給正確的,%% j分配給左邊的? – Sakura

+0

'FOR/F「TOKENS = 1 ,* DELIMS ==「...'!在命令行中鍵入'FOR /?'並檢查'FOR'文檔。 –

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

純批:

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。使用管道時也不需要。