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.

SomethingDark
  • 13,229
  • 5
  • 50
  • 55
Nicholas Chan
  • 381
  • 2
  • 3
  • 10

4 Answers4

13

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)

Stephan
  • 53,940
  • 10
  • 58
  • 91
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);
Stephen Quan
  • 21,481
  • 4
  • 88
  • 75
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.

Community
  • 1
  • 1
aschipfl
  • 33,626
  • 12
  • 54
  • 99
  • "_(I know it looks terrible):_" [Truer words...](https://www.goenglish.com/TruerWordsWereNeverSpoken.asp) – ruffin Jan 06 '23 at 21:51
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)

  • The first sentence says _errorlevel is that number OR HIGHER_ or _NOT that number or higher_ –  Dec 30 '15 at 08:55
  • `findstr` errorlevel doesn't give the count, but only `0` (found at least one) or `1` (found none). – Stephan Apr 18 '20 at 15:57