Batch - Compare variable with regular expression

こ雲淡風輕ζ 提交于 2019-12-18 06:12:32

问题


I'm doing a batch script that has to check if there are some programs installed on the computer. For that, I execute programName --version and I store the output in a variable. The problem is when I try to compare with a regular expression (only to know if this program exists in the machine). I'm trying this code, but does't work

>output.tmp node --version
<output.tmp (set /p hasNode= )
if "%hasNode%" == "[vV][0-9.]*" (echo Has node) else (echo You have to install node)

If I change the regular expression for the output of this command works properly, so I suppose that I'm doing a bad use of the regular expression (I've checked it and it's fine for the command's output)

Thanks four your help guys


回答1:


Batch/cmd does not support regexes directly. You have to use findstrfor that, for example:

echo %node% | findstr /r "[vV][0-9.]*" >nul 2>&1 && (echo contains) || (echo does not contain) or

echo %node% | findstr /r "[vV][0-9.]*" >nul 2>&1 if errorlevel 1 (echo does not contain) else (echo contains)

This trick delegates comparison to findstr and than uses return code (errorlevel) from it.
(please note that regexes findstr supports are also quite limited and has some quirks, more info http://ss64.com/nt/findstr.html)



来源:https://stackoverflow.com/questions/23169696/batch-compare-variable-with-regular-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!