我正在编写一个接收命令并运行它们的批处理脚本。我需要在输入结束时检查用户输入的字符串。例如,假设用户键入ECHO Hello World & ECHO ON
,并且存储此命令的变量为%CHO%
,如何在变量末尾找到& ECHO ON
?
我已经有办法在输入中找到ECHO ON &
,但我需要一种方法来检查& ECHO ON
是否在变量的末尾。如果我只是检查& ECHO ON
,那么该脚本很容易误认为& ECHO ONWARDS
或类似的内容,并认为它实际上是& ECHO ON
。
关于如何做到这一点的任何想法?
答案 0 :(得分:1)
试试这个 - 它也应该能够处理特殊符号(它使用endsWith子程序):
@echo off
:::example calls of :endsWith subroutine
call :endsWith abcdefgh fgh
echo %errorlevel%
call :endsWith abcdefgh abc
echo %errorlevel%
exit /b 0
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:endsWith [%1 - string to be checked;%2 - string for checking ]
@echo off
rem :: sets errorlevel to 1 if %1 ends with %2 else sets errorlevel to 0
setlocal EnableDelayedExpansion
set "string=%~1"
set "checker=%~2"
set LF=^
rem ** Two empty lines are required
rem echo off
for %%L in ("!LF!") DO (
for /f "delims=" %%R in ("!checker!") do (
set "var=!string:%%~R=%%L#!"
)
)
for /f "delims=" %%P in (""!var!"") DO (
set "temp=%%~P"
)
if "%temp%" EQU "#" (
endlocal & exit /b 1
) else (
endlocal & exit /b 0
)
goto :eof
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
您也可以使用FINDSTR
(可能会因为依赖外部命令而变慢):
echo abcdefgh| findstr /e "fgh" >nul 2>nul && (
echo ends with
)||(
echo does not ends with
)