Searching for specific characters within a string using a for loop to check time format in Batch

Refresh

March 2019

Views

37 time

1

I'm writing a script where a user has to put in a time. The issue I'm running into is that the user can enter anything and batch script will accept it. My idea to check for this was to extract where the colon should be in the time inputted and check if it's there with this:

SET check=%utime:2,1%
IF %check%==: [continue with script]

So that it'd skip the first two characters in say 01:00 and extract the semi colon, set it to check and then compare check to see if it was a colon or not. This works great but then I realized that a user could input anything with a colon in the third space and get past. For a first step my idea to check for this was to have a FOR loop check all the five possible spaces to see if they were empty or not with this code:

SET conf=1
FOR /L %%i IN (1,1,5) DO (
echo %%i
SET check=%utime:%%i,1%
IF [%check%] == [] SET conf=0
)

conf would be a true or false variable (0 or 1) that I could then evaluate with an IF statement to then see if it's a valid format. But what ended up happening is that conf was set to 0 but it was not correctly checking the characters within the time variable. Leaving the echo on I could see that check was not correctly being set meaning conf was always set to 0 no matter what was inputted from the user. Here is the code in question in context just in case (This portion is only meant to check for 5 characters being present):

:Start
SET /p utime=Please insert the time (hh:mm):
CALL :CheckTime
IF conf EQU 1 goto :Valid
ECHO Please enter a valid time!
GOTO :Start

:Valid
ECHO Thank you for entering a valid time!
PAUSE
EXIT

:CheckTime
SET conf=1
FOR /L %%i IN (1,1,5) DO (
echo %%i
SET check=%utime:%%i,1%
IF [%check%] == [] SET conf=0
)
EXIT /B

2 answers

1

Возможно , используя FindStrбудет вполне подходящим:

:Start
Set "uTime="
Set /P "uTime=Please insert the time (hh:mm): "
Set "uTime=%uTime:~,5%"
If Not Defined uTime GoTo :Start
Echo %uTime% |FindStr /R "[0-1][0-9]:[0-5][0-9] 2[0-3]:[0-5][0-9]">Nul||GoTo :Start
Echo Thank you for entering a valid time!
Pause
1

A little bit different approach then Compo.

:: Q:\Test\2018\06\14\SO_50860883.cmd
@Echo off
:Start
Set "MyTime="
SET /p MyTime=Please insert the time (hh:mm):
If not defined MYTime Exit /B 0
CALL :CheckTime "%MyTime%"|| (ECHO Please enter a valid time! &GOTO :Start)

ECHO Thank you for entering a valid time %MyTime% !
ECHO=
goto :Start

:CheckTime passed value not a fixed var
Echo=%~1|Findstr "^[0-9]:[0-5][0-9]$ ^[0-1][0-9]:[0-5][0-9]$ ^2[0-3]:[0-5][0-9]$" 2>&1>Nul || Exit /B 1

To not allow the input of a single digit hour change the last line to :

Echo=%~1|Findstr "^[0-1][0-9]:[0-5][0-9]$ ^2[0-3]:[0-5][0-9]$" 2>&1>Nul || Exit /B 1