如何限制批处理变量的长度

How to limit a batch variable's length

有什么方法可以限制批处理变量的长度吗?我的意思是,是否可以编写一个只允许 0 到 x 个字符的变量?因此,例如,如果我输入 123456 并且最大长度为 4,它将不会继续。我希望你能理解我的问题。 提前致谢。

根据aschipfl and rojo的建议演示批处理代码:

@echo off
setlocal EnableExtensions EnableDelayedExpansion
:UserPrompt
cls
set "UserInput="
set /P "UserInput=Enter string with a length between 1 and 4: "
if not defined UserInput goto UserPrompt
if not "!UserInput:~4!" == "" goto UserPrompt
echo/
echo String entered: !UserInput!
echo/
endlocal
pause

!UserInput:~4! 在执行批处理文件时被命令处理器替换为用户输入的从第五个字符开始的字符串。字符串值的第一个字符的索引值为 0,这是第五个字符为数字 4 的原因。如果用户输入的字符串不超过 4 个字符,则此字符串为空,否则此子字符串 不是 空,导致用户必须再次输入字符串。

延迟扩展用于避免用户输入包含奇数个双引号的字符串时语法错误导致批处理退出。

要了解使用的命令及其工作原理,请打开命令提示符 window,在其中执行以下命令,并仔细阅读为每个命令显示的所有帮助页面。

  • cls /?
  • echo /?
  • endlocal /?
  • if /?
  • pause /?
  • set /?
  • setlocal /?

如果您的意思是 "limit the length of a batch variable when it is read via SET /P command",那么您可以使用 this post 中描述的 ReadLine 子例程,它使用纯批处理文件命令模拟 SET /P 命令,并且只需插入最大长度限制.

@echo off
setlocal

call :ReadNChars string4="Enter 4 characters maximum: " 4
echo String read: "%string4%"
goto :EOF


:ReadNChars var="prompt" maxLen

rem Read a line emulating SET /P command
rem Antonio Perez Ayala

rem Initialize variables
setlocal EnableDelayedExpansion
echo > _
for /F %%a in ('copy /Z _ NUL') do set "CR=%%a"
for /F %%a in ('echo prompt $H ^| cmd') do set "BS=%%a"

rem Show the prompt and start reading
set /P "=%~2" < NUL
set "input="
set i=0

:nextKey
   set "key="
   for /F "delims=" %%a in ('xcopy /W _ _ 2^>NUL') do if not defined key set "key=%%a"

   rem If key is CR: terminate input
   if "!key:~-1!" equ "!CR!" goto endRead

   rem If key is BS: delete last char, if any
   set "key=!key:~-1!"
   if "!key!" equ "!BS!" (
      if %i% gtr 0 (
         set /P "=!BS! !BS!" < NUL
         set "input=%input:~0,-1%"
         set /A i-=1
      )
      goto nextKey
   )

   rem Insert here any filter on the key
   if %i% equ %3 goto nextKey

   rem Else: show and accept the key
   set /P "=.!BS!%key%" < NUL
   set "input=%input%%key%"
   set /A i+=1

goto nextKey

:endRead
echo/
del _
endlocal & set "%~1=%input%"
exit /B

但是,如果您想在其他情况下限制 Batch 变量的长度,例如 SET /A 或普通 SET 命令,则无法做到这一点。当然,你可以执行这样的命令,然后然后将变量值切割到最大长度,但这个过程是完全不同的。