批处理 - 比较变量和正则表达式 [英] Batch - Compare variable with regular expression

查看:183
本文介绍了批处理 - 比较变量和正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个批处理脚本,必须检查计算机上是否安装了某些程序。为此,我执行 programName --version 并将输出存储在变量中。问题是当我尝试与正则表达式进行比较时(仅知道该程序是否存在于机器中)。我正在尝试此代码,但无法正常工作

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)

谢谢你的四个帮助人员

推荐答案

批处理/ cmd不直接支持正则表达式。您必须使用 findstr ,例如:

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不包含)

echo%node%| findstr / r[vV] [0-9。] *> nul 2>& 1
如果errorlevel 1(echo不包含)else(echo contains)

这个技巧将比较委托给 findstr 而不是使用返回代码(errorlevel)。

(请注意,正则表达式 findstr 支持也非常有限并且有一些怪癖,更多信息 http://ss64.com/nt/findstr.html

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)

这篇关于批处理 - 比较变量和正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆