Dưới đây là một giải pháp thú vị mà không quan tâm có bao nhiêu hoặc những gì đặt tên = giá trị cặp được quy định. Bí quyết là thay thế mỗi dấu phẩy bằng ký tự linefeed để FOR/F sẽ lặp lại từng cặp name = value. Điều này sẽ hoạt động miễn là chỉ có một /
trong chuỗi.
@echo off
setlocal enableDelayedExpansion
set "str=MyProject/Architecture=32bit,BuildType=Debug,OS=winpc"
::Eliminate the leading project info
set "str=%str:*/=%"
::Define a variable containing a LineFeed character
set LF=^
::The above 2 empty lines are critical - do not remove
::Parse and set the values
for %%A in ("!LF!") do (
for /f "eol== tokens=1,2 delims==" %%B in ("!str:,=%%~A!") do set "%%B=%%C"
)
::Display the values
echo Architecture=%Architecture%
echo BuildType=%BuildType%
echo OS=%OS%
Với mã bit hơn, nó có thể phân tích cú pháp một cách có chọn lọc chỉ các cặp tên = giá trị mà chúng tôi quan tâm.
@echo off
setlocal enableDelayedExpansion
set "str=MyProject/Architecture=32bit,BuildType=Debug,OS=winpc"
::Eliminate the leading project info
set "str=%str:*/=%"
::Define a variable containing a LineFeed character
set LF=^
::The above 2 empty lines are critical - do not remove
::Define the variables we are interested in
set "vars=Architecture BuildType OS"
::Clear any existing values
for %%A in (%vars%) do set "%%A="
::Set the values
for %%A in ("!LF!") do (
for /f "eol== tokens=1,2 delims==" %%B in ("!str:,=%%~A!") do (
for %%D in (%vars%) do if "%%B"=="%%D" set "%%B=%%C"
)
)
::Display the values
for %%A in (%vars%) do echo %%A=!%%A!
16 giây và sạch hơn nhiều! Tôi ra khỏi phiếu bầu cho ngày hôm nay, vì vậy tưởng tượng +1 cho bây giờ; trở lại với một cuộc bỏ phiếu thực sự sau đó. – LittleBobbyTables