I've got a variable and I need to check if it has only captials. For Example:
ABCDEF should match
But ABcdef shouldn't
How can I do it?
I've got a variable and I need to check if it has only captials. For Example:
ABCDEF should match
But ABcdef shouldn't
How can I do it?
Use findstr and errorlevel. See the example below. Note that you might expect "^[A-Z]*$"
to work as the pattern, but it doesn't as mentioned here.
Also note there is no space between %X%
and |
character, this is important.
C:\>SET X=ABCDEF
C:\>SET Y=ABcdef
C:\>echo %X%| findstr "^[ABCDEFGHIJKLMNOPQRSTUVWXYZ]*$"
ABCDEF
C:\>echo %errorlevel%
0
C:\>echo %Y%| findstr "^[ABCDEFGHIJKLMNOPQRSTUVWXYZ]*$"
C:\>echo %errorlevel%
1
lessthanideal has a solution that will strictly verify that the string only contains capital letters. But I wonder if punctuation and or numerals should be allowed? If so, then it is better to check for the existence of a lower-case letter.
Also, you don't need to see the output of the FINDSTR command, so it can be redirected NUL. And you can use the &&
and ||
operators to detect success and failure.
I am using echo(
so that a blank line is echoed if the variable is undefined instead of ECHO is on.
. Most people use echo.
, but that form can fail under some circumstances, and echo(
never fails.
@echo off
setlocal
set x=ABC_123
set y=AbC_123
echo(%x%|findstr /v "[abcdefghijklmnopqrstuvwxyz]" >nul && (
echo %x% is Valid
) || (
echo %x% is Invalid
)
echo(%y%|findstr /v "[abcdefghijklmnopqrstuvwxyz]" >nul && (
echo %y% is Valid
) || (
echo %y% is Invalid
)