22
@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 4

15

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)

Sign up to request clarification or add additional context in comments.

Comments

5

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

Comments

1

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 Comment

"(I know it looks terrible):" Truer words... 😉
0

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 Comments

The first sentence says errorlevel is that number OR HIGHER or NOT that number or higher
findstr errorlevel doesn't give the count, but only 0 (found at least one) or 1 (found none).

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.