0
@echo off
:loop
set /p input="> "
echo %input%|find /i "my name is" >nul && echo That's a nice name.

How would I take input and if it has my name is in it it stores the name as a variable. My goal is to take there name and store it as a variable and use it when it reply.

A-Yamout
  • 9
  • 1
  • I'd ask what type of person would ever provide that within their reply? and to what specific question? It is already awkward enough to deal with the `set /p` input, so anything which tries to validate anything other than simple words or character sequences is bordering on pointless, and would be better performed using a language which has proper regular expression support and preferably less difficulty with poison characters. – Compo Dec 03 '20 at 01:37
  • You will probably need some of the following things: [sub-string substitution](https://ss64.com/nt/syntax-replace.html), [`for /F`](https://ss64.com/nt/for_f.html), [`if`](https://ss64.com/nt/if.html) and [`set`](https://ss64.com/nt/set.html)… – aschipfl Dec 03 '20 at 11:06

2 Answers2

0
set "name=Input error"
if "%input:my name is =%" neq "%input%" set "name=%input:my name is =%"
echo %name%

The if statement tests whether the string my name is is part of the value in input. If it is, then remove that string and the remainder is the name.

But, following @Compo's comments, this is very vulnerable, and in any case, who on Earth would reply my name is Fred Nurk to such a question? Fred Nurk would be the more likely reply.

Magoo
  • 77,302
  • 8
  • 62
  • 84
  • 1
    `if /i` would be beneficial. – Stephan Dec 03 '20 at 08:45
  • @Stephan : Um, no. The substitution is case-insensitive. Now fixing the RHS by putting in the closing quote (as I have now done) - *that's* beneficial. – Magoo Dec 03 '20 at 14:46
  • yes, the substitution is case insensitive - but the `if` comparison isn't. (I said `if /i`, not `set /i`). Whoever cares to answer with a full sentence, also might care to capitalize correctly (`My name is Fred Nurk`) – Stephan Dec 03 '20 at 14:52
  • @Stephan : The `if` expression works because the LHS expression substitutes *nothing* for the target string **regardless of case**. Only if the target string is present will the substitution be made, and the `neq` only occurs if the substitution occured. `if /i` will thus be harmless, but superfluous. – Magoo Dec 03 '20 at 23:18
  • yes - I see what you mean. `If` doesn't compare the string, but the (maybe) shortened string, where the shortening is case insensitive. I used to know this - brains work in strange ways from time to time... – Stephan Dec 04 '20 at 08:46
0

As already stated, if you're going to be taking input via set /p you want to be validating or restricting what a user can input. The below is a function that can be used to assign variables that match permitted findstr regex patterns.

:GetIN [ReturnVar] ["qouted findstr search pattern"]  [Optional:"/C" - required for patterns with spaces]
@Echo off
 SETLOCAL EnableExtensions EnableDelayedExpansion
rem - lines prefixed with ::: form part of this scripts Help Documentation. Do not remove.
> "%TEMP%\%~n0_help.~tmp" (For /F "Delims=" %%G in ('Type "%~f0"^| Findstr.exe /BLIC:":::" 2^> nul ')Do For /F "Tokens=1* Delims=:" %%v in ("%%G")Do Echo/^|%%v)
:::================================================================================================================
:::     [ GetIn Input function or standalone script for validating input with findstr regular expressions. ]
:::                     Version = 2.2        Release = October 2020       Author = T3RRY 
:::========================================= ^^^! important notes on usage ^^^! =========================================
:::          ^^^! Pipes not supported ^^^!
:::    ^     + Not suited for use with pipes due to forced loop for failed matches
:::  < ^^^! >   + Test your regex pattern to ensure it is valid for the required input
:::    v       format to prevent your user/s being stuck in a goto loop.
:::            Error output for invalid search patterns is not displayed.
:::          + EXIT.CODES - Errorlevel assessment after call:
:::            - Errorlevel 3 - User has failed to provide input * OR * regex pattern is
:::              invalid * OR * GetIn is a called label in a file that has recieved input
:::              from a pipe that has not been handeled before the call.
:::            - Errorlevel 2 - GetIn is a script that has been invoked by a pipe
:::            - Errorlevel 1 - GetIn help has been Invoked * OR * GetIn has been called
:::              without Arg 2 for Regex Pattern
:::            - Errorlevel 0 - Input has been assigned that matches the regex Pattern
:::================================================================================================================
rem [* Display GetIn Usage with findstr regex info and practical examples *]
>> "%TEMP%\%~n0_help.~tmp" (
  Echo/^| USAGE: Call %~0 [ReturnVar] ["findstr search pattern"] [Optional:"/C" -required for patterns with spaces]
  Echo/^|================================================================================================================
  Echo/^| Examples [ Description is replaced with Arg 1-ReturnVar ]:
  Echo/^|
  Echo/^|    Call %~0 4-Digit-Number "[0-9][0-9][0-9][0-9]"
  Echo/^|    Call %~0 Alphanumeric-String "[0-9a-zA-Z]*"
  Echo/^|    Call %~0 semicolon-delimited-hexadecimal-String "[0-9a-fA-F][0-9a-fA-F][:][0-9a-fA-F][0-9a-fA-F]"
  Echo/^|    Call %~0 AlphaString-with-3-Digit-Numeric-suffix "[a-zA-Z]*[0-9][0-9][0-9]"
  Echo/^|    Call %~0 list-of-delimited-words "[a-zA-Z, ]*" /C
  Echo/^|    Call %~0 pair-of-delimited-numbers "[0-9]*[, ][0-9]*" /C
  Echo/^|
  Echo/^|    ^^     Limit of 15 character class expressions applies
  Echo/^|  ^< ^^^! ^>   Case sensitive classes should use actual letters as [STRING] instead of range [A-Z]
  Echo/^|    v     See: https://stackoverflow.com/a/20159191/12343998
  Echo/^|                                                     -Note: %~0 does not support Input from pipes.
  Echo/^|----------------------------------------------------------------------------------------------------------------
  For /F "Delims=" %%G in (' Findstr.exe /? ^| More +33 ') Do Echo/^|  %%G
  Echo/^|  https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/findstr
  Echo/^|  recommended reference: https://stackoverflow.com/questions/8844868/
   Echo/\================================================================================================================
 )
(Set LF=^

%= Linefeed. do not modify. =%)
Set "Exit.Code=0"
rem [ test if standalone script - if so test if accessed by pipe; reject execution if true ]
 If "%~0" == "%~n0" For %%G in (!cmdcmdline!)Do Echo/%%~G|Findstr.exe /LIC:"/S" > nul 2> nul && (Set "Exit.Code=2" & Goto :Usage)
:retry
 Del /Q "%TEMP%\%~n0_validate.~tmp" 2> nul
 If !Exit.Code! GTR 5 Goto :Usage
 Set "rVar=" & Set "_C=0" & Set "_S=0"
 If "%~2" == "" GOTO :Usage
 Setlocal DISABLEdelayedExpansion & rem ::: dispay occurances of carets [^] in pattern
 Endlocal & Set "Pattern=%~2"
rem /* optional prompt */
rem /*   Set /P "rVar=Input Format for %1:!LF!!Pattern!!LF!!LF!Enter %1: " */
 > "%TEMP%\%~n0_validate.~tmp" (Echo/!rVar!)
 If /I "%~3" == "/C" (
  TYPE "%TEMP%\%~n0_validate.~tmp"| findstr.exe /RXC:"%~2" > nul || (Set /A "Exit.Code+=1" & <nul Set /P"= ^! Invalid value.!LF!" & Goto :Retry)
 ) Else (
  TYPE "%TEMP%\%~n0_validate.~tmp"| findstr.exe /RX "^%~2$" >nul || (Set /A "Exit.Code+=1" & <nul Set /P"= ^! Invalid value.!LF!" & Goto :Retry)
 )
 Echo/%1: [!rVar!] Accepted
 If defined echostate Echo on
 ENDLOCAL & @Set "%~1=%rVar%"
 Del /Q "%TEMP%\%~n0_validate.~tmp"
 Exit /B 0
:Usage
 Mode 1000
 If "%Exit.Code%" == "0" (Set "Exit.Code=1")
 If "%Exit.Code%" == "2" (
  >> "%TEMP%\%~n0_help.~tmp" (
    Echo/-------------------------------              ^^! pipes not supported ^^!              -------------------------------
    Echo/=================================================================================================================
 ))
If %Exit.Code% GTR 5 (
  >> "%TEMP%\%~n0_help.~tmp" (
   Echo/-------------------------------      ^^! Attempt limit exceeded. Input rejected ^^!   -------------------------------
   Echo/-------------------------------              ^^! pipes not supported ^^!              -------------------------------
   Echo/=================================================================================================================
  )
  Set "Exit.Code=3"
 )
 Type "%TEMP%\%~n0_help.~tmp" | ( More )
 Del /Q "%TEMP%\%~n0_help.~tmp" 2> nul
ENDLOCAL & exit /B %Exit.Code%
rem ::: [ ------------------------------------------------------------------------------------------------- End GetIn ]
SiHa
  • 7,830
  • 13
  • 34
  • 43
T3RR0R
  • 2,747
  • 3
  • 10
  • 25