batch code to test if script contains anything oth

2019-07-13 17:40发布

问题:

I was wondering if it is possible to test a variable to see if it contains anything other than Letters and numbers? I need to have this in order to limit username specs. I have a kind of example script below.

 :top
echo enter a name
set /p name=">"
If contains (Anything other than letters/numbers/dashes) echo Invalid Name. & goto top
echo thank you!
pause

Thanks everyone!

Edit: I assume this is probably a duplicate, however I do not know what to search for to find other posts... Whenever I searched anything related to my question it brought up find and replace in text files or something else unrelated. If anyone can find a duplicate please let me know and I will close this question. Thank you.

回答1:

This allows only letters, numbers, and dashes:

@echo off & setlocal

:top
set /P "name="Enter a name: "
setlocal enabledelayedexpansion
echo(!name!| findstr /i "[^a-z0-9-]" >NUL && (
    endlocal
    set /P "=Invalid name. " <NUL
    goto top
)

endlocal
echo Thank you %name%!
pause


回答2:

This work for the majority of ascii characters. It may have some caveats.

@echo off
set /p "name=Enter a name>"
set "test=%name%"
FOR %%G IN ( a b c d e f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9 ) do (
    IF DEFINED test call set "test=%%test:%%G=%%"
)
IF DEFINED test (
    echo Invalid characters in username:"%test%"
) else (
    echo Good Username: "%name%"
)
pause