问题
So I'm working on a Windows Batch script and I want to know if an input string (the name of a file) is exactly four letters long. I want to do it with regular expressions or string matching.
I tried the following but it didn't work...
for /R "%windir%\system32" %%f in (*) do (
set filename=%%~nf
if not "!filename!"=="!filename:[a-z][a-z][a-z][a-z]=!" (
echo %%~nf
)
)
So my code loops through all the files in \system32. The files like mode.com should be echoed, but it's not the case.
回答1:
This works:
dir /B "%windir%\system32" | findstr "^[a-z][a-z][a-z][a-z]\."
Tested on Windows 10
回答2:
Aacini's answer is the best when no recursion is required.
Just in case you need something more flexible (but way slower):
@echo off
for /R "%windir%\system32" %%f in (*) do (
echo %%~nf|findstr /rix "[a-z][a-z][a-z][a-z]" >nul && (
echo %%~ff has a 4 letter filename: %%~nf and a size of %%~zf Bytes
)
)
回答3:
As implied in my comment, and assuming four characters, not four alphabetic characters:
@For /R "%__AppDir__%" %%A In (*)Do @(Set "FN=%%~nA"
SetLocal EnableDelayedExpansion
If Not "%%~nA"=="!FN:~,3!" If "%%~nA"=="!FN:~,4!" Echo %%~nA
EndLocal)
And here's a possible alternative, for four alphabetic characters. Run it 'As administrator' if you're really trying to parse all files inside \Windows\System32\
, (not essential but may pick up more files):
@Dir /B/S/A-D "%__AppDir__%" 2>NUL|"%__AppDir__%findstr.exe" "\\[a-Z][a-Z][a-Z][a-Z]\.[^\.]*$ \\[a-Z][a-Z][a-Z][a-Z]$"
You could put that inside a for-loop if, for some inexplicable reason, you only want only the basenames:
@For /F "EOL=?Tokens=*" %%A In ('Dir /B/S/A-D "%__AppDir__%" 2^>NUL^|"%__AppDir__%findstr.exe" "\\[a-Z][a-Z][a-Z][a-Z]\.[^\.]*$ \\[a-Z][a-Z][a-Z][a-Z]$"')Do @Echo(%%~nA
回答4:
Try this:
dir /b C:\Windows\system32 | findstr /r "[a-z][a-z][a-z][a-z]"
The problem in your code was regular expression using style. You need to use findstr
for regular expressions.
来源:https://stackoverflow.com/questions/58599651/how-can-i-see-if-a-string-is-four-letters-long-windows-batch