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.

4 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)

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);
0

Stephan's answer is correct in terms of support for regular expression. However, it does not regard a bug of findstr concerning character classes like [a-z] -- see this answer by dbenham.

To overcome this you need to specify this ( I know it looks terrible):

echo %var%|findstr /R "^[abcdefghijklmnopqrstuvwxyz][abcdefghijklmnopqrstuvwxyz]$ ^[abcdefghijklmnopqrstuvwxyz][abcdefghijklmnopqrstuvwxyz][abcdefghijklmnopqrstuvwxyz]$"

This truly matches only strings consisting of two or three lower-case letters. Using ranges [a-z] would match lower- and upper-case letters except Z.

For a complete list of bugs and features of findstr, reference this post by dbenham.

1

errorlevel is that number OR HIGHER.

Use following.

if errorlevel 1 if not errorlevel 2 echo It's just one.

See this

Microsoft Windows [Version 10.0.10240]
(c) 2015 Microsoft Corporation. All rights reserved.

C:\Windows\system32>if errorlevel 1 if not errorlevel 2 echo It's just one.

C:\Windows\system32>if errorlevel 0 if not errorlevel 1 echo It's just ohh.
It's just ohh.

C:\Windows\system32>

If Higher than one and not higher than n+1 (2 in this case)

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest