So I am having trouble with this line of code, which is meant to check if user input matches the given options.
set /p "myVar=---> "
echo %myVar%|findstr /ix "red:Red:blue:Blue">nul && (
echo %myVar% matched
) || (
echo %myVar% not matched
)
Is there a way I can go it like the above or any other way?
You could make use of the fact that for /F
returns an exit code of 1
in case of zero iterations:
set /P VAR="Enter something: " || ((echo Empty input!) & exit /B)
(for /F "delims=AaEeIiOoUuYy eol=y" %%K in ("%VAR%") do rem/) && (
echo No match found!
) || (
echo Match encountered.
)
If the input consists only of characters listed after delims=
, the for /F
loop does not iterate and returns an exit code of 1
; the command behind &&
only executes in case the exit code is 0
, the command behind ||
only executes in case the exit code is not 0
.
If no input is provided, set /P
sets the exit code to 1
.
Here is a basic example of what you want to do. I have not tested in DOS since I do not have any VM (or very old computer) right here, but IIRC this should work in plain DOS as well.
@echo off
if %var% == A GOTO :anything
if %var% == E GOTO :anything
if %var% == I GOTO :anything
if %var% == O GOTO :anything
if %var% == U GOTO :anything
if %var% == Y GOTO :anything
goto end
:anything
echo anything
:end
I think, choice
is your best friend here. But if you want to do it without choice
(it isn't available in all Windows versions):
set /p "myVar=---> "
echo %myVar%|findstr /ix "a e i o u y">nul && (
echo %myVar% matched
) || (
echo %myVar% not matched
)
It asks for input and checks if it is exactly one of the characters from the list, ignoring capitalization.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.