2015-12-30 104 views
11
@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 

我試圖驗證應該包含2或3個字母的輸入。但我試過所有可能的答案,它只運行if error level 1 (echo does not contain)正則表達式來匹配批量腳本中的變量

有人可以幫助我。非常感謝。

回答

7

findstr沒有充分REGEX支持。特別是沒有{Count}。你必須使用一種解決方法:

echo %var%|findstr /r "^[a-z][a-z]$ ^[a-z][a-z][a-z]$" 

其搜索^[a-z][a-z]$ OR ^[a-z][a-z][a-z]$

(注:有%var%|之間沒有空間 - 這將是字符串的一部分)

0

errorlevel是那個數字或更高。

使用以下。

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

(在這種情況下2)參見本

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> 

如果超過一個大於n + 1高等及不高於

+1

..我不明白它 –

+0

第一句_errorlevel是數字或HIGHER_或_NOT該號碼或higher_ – 2015-12-30 08:55:29

0

Stephan's answer是正確的支持正則表達式。但是,它不考慮關於[a-z]等字符類的findstr的錯誤 - 請參閱this answer by dbenham

爲了克服這一點,你需要指定這個(我知道這看起來很可怕):

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

這確實只匹配由兩個或三個小寫字母串。使用範圍[a-z]將匹配較低的大寫字母,但Z除外。

有關缺陷和findstr的功能的完整列表,請參考this post by dbenham

0

由於其他答案不是針對findstr,如何運行cscript?這樣做可以讓我們使用合適的正則表達式引擎。

@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 

match.js被定義爲:

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