Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match a variable in Batch scripting

@echo off

SET /p var=Enter: 
echo %var% | findstr /r "^[a-z]{2,3}$">nul 2>&1
if errorlevel 1 (echo does not contain) else (echo contains)
pause

I'm trying to valid a input which should contain 2 or 3 letters. But I tried all the possible answer, it only runs if error level 1 (echo does not contain).

Can someone help me please. thanks a lot.

like image 340
Nicholas Chan Avatar asked Dec 30 '15 06:12

Nicholas Chan


2 Answers

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)

like image 121
Stephan Avatar answered Oct 16 '22 14:10

Stephan


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);
like image 26
Stephen Quan Avatar answered Oct 16 '22 15:10

Stephen Quan