使用findstr在批处理文件中查找正则表达式

时间:2015-06-13 13:11:53

标签: batch-file findstr

我想创建一个批处理文件来检查文件名是否按照某些规则编写。 文件名包含一些由连字符分隔的参数(字母和数字),如: FIN73-INV-2015-ANN

我想检查前两个参数(部门名称和文档类型),最重要的是检查是否错误地写了超过1次。例如FIN73 - INV-2015-ANN

我已尝试使用命令FINDSTR,但似乎不起作用,因为即使有两个连字符,errorlevel也总是0,就像在这种情况下一样:

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

你有更多建议吗?

谢谢

2 个答案:

答案 0 :(得分:0)

代表<StartOfString><letter><letter><letter><number><number><hyphen><letter>

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

如果不知道字母/数字的数量:FINDSTR /i "^[a-z]*[0-9]*-[a-z]"

答案 1 :(得分:0)

@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

输出示例:

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