Regex to match a variable in Batch scripting
Since other answers are not against findstr
, howabout running cscript
? This allows us to use a proper Javascript regex engine.
@echo off
SET /p var=Enter:
cscript //nologo match.js "^[a-z]{2,3}$" "%var%"
if errorlevel 1 (echo does not contain) else (echo contains)
pause
Where match.js
is defined as:
if (WScript.Arguments.Count() !== 2) {
WScript.Echo("Syntax: match.js regex string");
WScript.Quit(1);
}
var rx = new RegExp(WScript.Arguments(0), "i");
var str = WScript.Arguments(1);
WScript.Quit(str.match(rx) ? 0 : 1);
findstr
has no full REGEX Support. Especially no {Count}
. You have to use a workaround:
echo %var%|findstr /r "^[a-z][a-z]$ ^[a-z][a-z][a-z]$"
which searches for ^[a-z][a-z]$
OR ^[a-z][a-z][a-z]$
(Note: there is no space between %var%
and |
- it would be part of the string)