How to compare 2 strings in batch and determine if variable is alphabets
19,593
If you want to check if a variable contains only letters you could use findstr
, like this:
set var=Abc
echo %var%|findstr "^[A-Za-z]*$" >nul
if %errorlevel% == 0 (echo Variable is alphabetical)
How it works
The variable is echoed and then piped to the findstr
command, which will use a regular expression to match alphabetical characters:
-
^
matches beginning of line; -
[A-Za-z]
defines a character class which matches any character from A to Z, both upper case and lower case; -
*
repeats zero or more occurrences of the previous class; -
$
matches end of line.
The %errorlevel%
variable will be set to 0
if there's a match, or 1
otherwise. The findstr
output will be then redirected to nul
, thus ignored.
References
Related videos on Youtube
Author by
SlonCHL
Updated on September 18, 2022Comments
-
SlonCHL over 1 year
I have this code
for /l %%a in (0, 1, 25) do ( if /i !TextAlphabet!==!Alphabet[%%a]! ( set AlphabetNumber=%%a ) )
!Alphabet[]!
is an array containing alphabets.I tried echoing
!TextAlphabet!
and!Alphabet[%%a]!
and when they are the same,%AlphabetNumber%
is still the value I set before the loop.I tried checking for white spaces in my variables but found none.
I also tried adding the variables in a "" tag.
-
DrColossos about 10 yearsThis question appears to be off-topic because it is about programming and belongs on Stack Overflow. Try stackoverflow.com/help/how-to-ask
-
slhck about 10 years@KevinPanko The question is fine here. We allow scripting questions that pertain to power user environments and system administration.
-