Batch 没有任何正式的复杂数据结构,如数组、列表或对象。但是你可以模仿他们。这是一个有效的解决方案,它定义了与您的问题中的格式几乎相同的组。
@echo off
setlocal enableDelayedExpansion
::Here is a small loop to test the routine
for %%N in (822,823,883,835,856,863,880,884) do (
call :assignGroup %%N
echo %%N is in group !group!
)
exit /b
:assignGroup CaseNumber
:: The returning value is contained in variable GROUP
set group=0
for %%A in (
"822-824,829,845,851,859,864,867"
"826-828,830-839,843-844,847-850,852-854,860-862,883"
"855-858,861,863,865"
"877-882,884"
) do (
set /a group+=1
for %%B in (%%~A) do (
for /f "tokens=1,2 delims=-" %%C in ("%%B") do (
if "%%C"=="%~1" exit /b
if "%~1" gtr "%%C" if "%~1" leq "%%D" exit /b
)
)
)
::no group found so undefine the var
set "group="
exit /b
上述解决方案适用于偶尔调用。但是,如果您要调用该例程数千次,那么最好用分配的组号初始化一个有效值数组。然后每个测试都直接读取值,而不必调用例程。但是,有可能滥用这种技术。分配足够的值,每个变量分配变得越来越慢。您可能还会花费更多时间来设置数组而不是实际测试值。
[].
请注意,变量名称中的字符没有意义。它们可以从变量名中去掉,代码的功能也相同。它们只是为了帮助理解变量的意图。
@echo off
setlocal enableDelayedExpansion
::initialize a sparse "array" that assigns a group to each valid case #
set group=0
for %%A in (
"822-824,829,845,851,859,864,867"
"826-828,830-839,843-844,847-850,852-854,860-862,883"
"855-858,861,863,865"
"877-882,884"
) do (
set /a group+=1
for %%B in (%%~A) do (
for /f "tokens=1,2 delims=-" %%C in ("%%B") do (
if "%%D"=="" (
set case[%%C].group=!group!
) else for /l %%N in (%%C 1 %%D) do (
set case[%%N].group=!group!
)
)
)
)
::Now test some values
for %%N in (822,823,883,835,856,863,880,884,900) do (
if defined case[%%N].group (
echo %%N is in !case[%%N].group!
) else (
echo %%N is not in a group
)
)
exit /b