批处理文件If语句使用正则表达式

时间:2015-12-04 17:24:07

标签: regex batch-file if-statement

我有一个批处理文件首先检查外部文件以查看构建的源分支然后运行if else if语句运行正则表达式以匹配源分支,然后确定构建的位置将部署:

@echo off
setlocal enabledelayedexpansion
set SEPARATOR=/
set filecontent=
for /f "usebackqdelims=" %%a in ("BuildBranch.txt") do (
  set currentline=%%a
  set filecontent=!filecontent!%SEPARATOR%!currentline!
)

echo %filecontent%

If NOT "%filecontent%"=="develop(.*)" (
    echo Deploying to dev DEVELOP
) else If NOT "%filecontent%"=="^.feature(.*)" (
    echo Deploying to dev FEATURE
) else If NOT "%filecontent%"=="master(.*)" (
    echo Deploying to integration MASTER
) else If NOT "%filecontent%"=="^.hotfix(.*)" (
    echo Deploying to integration HOTFIX
)

pause

我通过regex101网站运行了每个正则表达式,但可能仍然存在问题。我的主要问题是,无论何时运行我的批处理文件,它只会运行If statements中的第一个。变量%filecontent%feature/MyNewFeature,因此应该看到它与第一个if语句不匹配,然后继续第二个语句。我不知道这是我的正则表达式还是if statements的问题。

1 个答案:

答案 0 :(得分:3)

IF不支持正则表达式匹配。但您可以尝试以下方法:

echo %filecontent% | >nul findstr /i /r /c:"develop.*" || ( echo Deploying to dev DEVELOP )
echo %filecontent% | >nul findstr /i /r /c:"^.feature.*" || ( echo Deploying to dev FEATURE )
echo %filecontent% | >nul findstr /i /r /c:"master.*" || ( echo Deploying to dev MASTER )
echo %filecontent% | >nul findstr /i /r /c:"^.hotfix.*" || ( echo Deploying to dev HOTFIX )

从那里你可以围绕findstr命令构建,因为它可以匹配一些正则表达式(不是高级的),与||运算符一起,用于案例对于if NOT的案例,&&if运算符。{/ p>

希望它有所帮助。

相关问题