Use of findstr to seach regular expression in a batch file

524 views Asked by At

I would like to create a batch file to check if the file name has been written following certain rules. The file name contains some parameters (letters and numbers) splitted by an hyphen character like : FIN73-INV-2015-ANN

I would like to check the first two parameters (department name and document type) and above all check if the hypen has been written more than 1 time by mistake . e.g. FIN73--INV-2015-ANN

I have tried with the command FINDSTR but it seems that doesn't work because even if there are two hyphens the errorlevel is always 0 like in this case:

echo FIN73--INV-2015-ANN|FINDSTR /i "^[a-z]-[a-z]"

Do you have more suggestions ?

Thank you

2

There are 2 answers

0
Aacini On
@echo off
setlocal

rem Define valid departments and types, enclosed by slashes
set "departments=/FIN73/FIN83/"
set "types=/INV/INB/"

call :CheckFilename "FIN73-INV-ANN"
call :CheckFilename "FIN73--INV-2015-ANN"
call :CheckFilename "FIN93-INV-2015-ANN"
call :CheckFilename "FIN73-INX-2015-ANN"
call :CheckFilename "FIN73-INV-2015-ANN"

goto :EOF


:CheckFilename
setlocal EnableDelayedExpansion

set "filename=%~1"
echo/
echo Checking "%filename%"

rem Separate the filename in parts at hyphen
set i=0
for %%a in ("%fileName:-=" "%") do (
   set /A i+=1
   set "part[!i!]=%%~a"
)
if %i% lss 4 (
   echo Error: missing parts
) else if %i% gtr 4 (
   echo Error: duplicated hyphen
) else if "!departments:/%part[1]%/=!" equ "%departments%" (
   echo Error: invalid department: %part[1]%
) else if "!types:/%part[2]%/=!" equ "%types%" (
   echo Error: invalid type: %part[2]%
) else (
   echo Name correct
)
exit /B

Output example:

Checking "FIN73-INV-ANN"
Error: missing parts

Checking "FIN73--INV-2015-ANN"
Error: duplicated hyphen

Checking "FIN93-INV-2015-ANN"
Error: invalid department: FIN93

Checking "FIN73-INX-2015-ANN"
Error: invalid type: INX

Checking "FIN73-INV-2015-ANN"
Name correct
0
Stephan On

for <StartOfString><letter><letter><letter><number><number><hyphen><letter>

use FINDSTR /i "^[a-z][a-z][a-z][0-9][0-9]-[a-z]"

If the count of letters/numbers are not known: FINDSTR /i "^[a-z]*[0-9]*-[a-z]"