我无法理解如何解决这个问题。得到以下代码:
:userinfo
set U=U
set /p EmployeeID=Please enter Employee ID:
for /f "tokens=1* delims=0123456789XC" %%a in ("A0%EmployeeID:"=%") do if not "%%b"=="" echo Only numbers, except X and C, case sensitive! && goto userinfo
它工作正常,但我想将输入字符限制为7个字符。意味着它需要7个字符 - 而不是最多7个字符。
我尝试使用if not "!EmployeeID:~7! == "" echo 7 characters required. & goto userinfo
,但这不起作用。
我确信这是一件很简单的事情......
答案 0 :(得分:0)
稍微不同的方法怎么样:
SET /P EmployeeID=Please enter Employee ID:
IF %EmployeeID:~-7% NEQ %EmployeeID% GOTO :userinfo
ECHO(%EmployeeID%|FINDSTR/R "[^0-9XC]" && (
ECHO(Only numbers, except X and C, case sensitive!
GOTO :userinfo)
如果您的意图不是限制而是限制,那么您可以检查是否有八个字符或第七个字符:
:userinfo
SET /P EmployeeID=Please enter Employee ID:
IF "%EmployeeID:~6,1%" NEQ "" (IF "%EmployeeID:~7,1%" EQU "" (
ECHO(%EmployeeID%|FINDSTR/R "[^0-9XC]" && (
ECHO(Only numbers, except X and C, case sensitive!
) || (GOTO :continue)))
GOTO :userinfo
:continue
SET U=U
答案 1 :(得分:0)
如果字符串不超过7个字符,则条件if "!EmployeeID:~7!"==""
的计算结果为 true (假设由!!
启用delayed expansion)。
要解决您的任务,只需应用第二个条件:if not "!EmployeeID:~6!"==""
true ,以防字符串长度至少为7个字符。
然后连接两个条件:
:userinfo
set /p EmployeeID="Please enter Employee ID: "
for /f "tokens=1* delims=0123456789XC" %%a in ("A0%EmployeeID:"=%") do (
if not "%%b"=="" (
echo Only numbers, except X and C, case sensitive^^!
goto userinfo
)
)
if "!EmployeeID:~7!"=="" if not "!EmployeeID:~6!"=="" (
rem Both conditions fulfilled, so continue
goto continue
) else (
echo 7 characters required.
goto userinfo
)
:continue
另一种方法是使用findstr
,您可以对其进行字符集和长度检查,如下所示:
:userinfo
set "EmployeeID="
set /p EmployeeID="Please enter Employee ID: "
echo(!EmployeeID!|findstr "^[0-9XC][0-9XC][0-9XC][0-9XC][0-9XC][0-9XC][0-9XC]$" 2> nul || (
echo 7 characters, only numbers, X and C, case-sensitive^^!
goto :userinfo
)
答案 2 :(得分:0)
这种不同的方法有几个优点:
此方法的唯一缺点是无法删除最后一个字符,但使用其他密钥,不 BS常用密钥时,可以使用其他代码。
@echo off
setlocal EnableDelayedExpansion
set "chars= 0123456789XC"
set "ID="
echo Enter digits 0-9 and *uppercase* "X" or "C" letters only^^!
set /P "=Please enter Employee ID: " < NUL
for /L %%i in (1,1,7) do (
choice /C %chars% /N /CS > NUL
for %%e in (!errorlevel!) do set "char=!chars:~%%e,1!"
set /P "=!char!" < NUL
set "ID=!ID!!char!"
)
echo/
echo/
echo Employe ID: %ID%