批量扫描子字符串

时间:2014-07-22 09:35:35

标签: windows batch-file cmd

我是批处理的新手,我正在尝试为项目制作一个“大脑般的”程序,它应该能够完成简单的简短对话。我正在使用set / p向用户提问,例如:

set /p a= Hello: 

我希望能够看到用户是否在答案中说出了一个特定字词,以帮助确定计算机将回复的内容。

感谢。

4 个答案:

答案 0 :(得分:2)

@echo off
set "specific_word=something"

set /p a= Hello: 


setlocal EnableDelayedExpansion
if /I not "!a:%specific_word%=!" EQU "!a!" (
    echo it contains the word
) else (
    echo it does not contain the word
)


echo %a%|find /i "%specific_word%" >nul 2>&1

echo --OR--

if errorlevel 1 (
    echo it does not contain the word

) else (
    echo it contains the word
)

IF方法更快。

答案 1 :(得分:2)

不是防弹代码,只是一个骨架。此代码测试"字的存在"输入文字中的单词

@echo off

    setlocal enableextensions disabledelayedexpansion

:input
    set "typed="
    set /p "typed=what? "
    if not defined typed goto :input

    rem Option 1 - Use find 
    echo( %typed% | find /i " word " >nul 
    if not errorlevel 1 echo FIND : "word" has been used 

    rem Option 2 - Use substring replacement
    set "text= %typed% "
    if not "%text: word =%"=="%text%" (
        echo IF   : "word" has been used
    )

    rem Option 3 - Tokenize the input
    set "text=%typed:"= %"
    for %%a in ("%text: =" "%") do (
        if /i "%%~a"=="word" echo FOR  : "word" has been used
    )

    endlocal

在需要的地方添加了有条件的空格以确保" word"内部没有找到"剑"。

答案 2 :(得分:1)

IF无法帮助您,因为批处理没有本地子字符串功能。但你可以通过一个小技巧来模仿它:

set a=user inputted something with a word in it.
echo %a%|find /i "word" >nul && (echo there is "word" in the input)

/i告诉它忽略大写

>nul告诉它不要在屏幕上显示它的发现

&&充当"如果find成功,那么......"

答案 3 :(得分:1)

可以使用find命令

它不是很优雅,但你可以使用一系列FIND命令和if语句。

@echo off
set /p a= "Hello: "

echo %a% | C:\Windows\System32\FIND /I "Hi" >  nul 2>&1
set FIND_RC_0=%ERRORLEVEL%

echo %a% | C:\Windows\System32\FIND /I "Howdy" > nul 2>&1
set FIND_RC_1=%ERRORLEVEL%

if "%FIND_RC_0%" == "0" (
    set /p b= "How are you today?: "
)

if "%FIND_RC_1%" == "0" (
    set /p b= "How you doing partner?: "
)