简体   繁体   English

确认用户输入是几个允许的单词之一

[英]Verify that user input is one of several allowed words

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: 您可以利用以下事实: for /F ,在零迭代的情况下返回退出代码1

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 ; 如果输入仅包含delims=之后列出的字符,则for /F循环不会进行迭代,并返回退出代码1 the command behind && only executes in case the exit code is 0 , the command behind || &&后面的命令仅在退出代码为0时执行, ||后面的命令 only executes in case the exit code is not 0 . 仅在退出代码不为0情况下执行。
If no input is provided, set /P sets the exit code to 1 . 如果未提供任何输入,则set /P将退出代码设置为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. 我没有在DOS中进行测试,因为我这里没有任何VM(或非常旧的计算机),但是IIRC也应在纯DOS中工作。

@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. 我认为, choice是您最好的朋友。 But if you want to do it without choice (it isn't available in all Windows versions): 但是,如果您想不做choice (并非在所有Windows版本中都可用):

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. 它要求输入并检查它是否正是列表中的字符之一,而忽略大小写。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM