如何在批处理文件中检查变量是否包含特殊字符

ace*_*cer 2 windows batch-file

如何检查批处理文件中的变量是否包含特殊字符?例如,如果我的变量包含文件名,则文件名不应包含\/ < > | : * " ?此类字符。

@echo off
set param="XXX"
echo %param%| findstr /r "^[^\\/?%*:|"<>\.]*$">nul

if %errorlevel% equ 0 goto :next
echo "Invalid Attribute"

:next
echo correct
Run Code Online (Sandbox Code Playgroud)

我使用此链接作为参考正则表达式来验证文件夹名称和文件名

Jos*_*efZ 6

echo %param%| findstr /r ...甚至不能使用echo !param!| findstr /r ...。有关如何解析和处理管道的更多信息,请查看此问题和答案:为什么在管道代码块内时延迟扩展失败

使用辅助(临时)文件如下:

@ECHO OFF
SETLOCAL EnableExtensions EnableDelayedExpansion
:testloop
  set "param="
  set /P "param=string to test (hit <Enter> to end)> "
  if not defined param goto :endtest
  >"%temp%\33605517.txt" echo(!param!

  rem next line for debugging purposes
  for /F "usebackq delims=" %%G in ("%temp%\33605517.txt") do set "_marap=%%G"

  findstr /r ".*[<>:\"\"/\\|?*%%].*" "%temp%\33605517.txt" >nul 

  if %errorlevel% equ 0 (
    echo !errorlevel! Invalid !param! [!_marap!]
  ) else (
    echo !errorlevel! correct !param! [!_marap!]
  )
  goto :testloop
:endtest
ENDLOCAL
goto :eof
Run Code Online (Sandbox Code Playgroud)

.*[<>:\"\"/\\|?*%%].*正则表达式解释

  • .* - 字符串前面的任何字符出现零次或多次;
  • [<>:\"\"/\\|?*%%] 一组保留字符中的任何一个字符:
    • < (少于);
    • > (比...更棒);
    • : (冒号);
    • "(双引号)转义为\"\"(findstr 和批处理解析器);
    • / (正斜杠);
    • \(反斜杠)转义为\\(findstr);
    • | (垂直杆或管);
    • ? (问号);
    • * (星号);
    • %(百分号)转义(用于批处理解析器)为%%;事实上,%它不是为NTFS文件系统保留的,而是需要在纯cmd脚本和/或批处理脚本中进行特殊转义;
  • .* - 字符串末尾的任何字符出现零次或多次。

这里有更多关于 SO 的一些问题的链接,其中包含 Aacini、DBenham、Jeb(以及其他人)的详尽答案。引人入胜、引人入胜的阅读……

并详细介绍如何命令行参数解析大卫Deley,©2009(更新2014)

输出

string to test (hit <Enter> to end)> n<m
0 Invalid n<m [n<m]
string to test (hit <Enter> to end)> n>m
0 Invalid n>m [n>m]
string to test (hit <Enter> to end)> n:m
0 Invalid n:m [n:m]
string to test (hit <Enter> to end)> n/m
0 Invalid n/m [n/m]
string to test (hit <Enter> to end)> n\m
0 Invalid n\m [n\m]
string to test (hit <Enter> to end)> n|m
0 Invalid n|m [n|m]
string to test (hit <Enter> to end)> n?m
0 Invalid n?m [n?m]
string to test (hit <Enter> to end)> n*m
0 Invalid n*m [n*m]
string to test (hit <Enter> to end)> n"m
0 Invalid n"m [n"m]
string to test (hit <Enter> to end)> nm
1 correct nm [nm]
string to test (hit <Enter> to end)> nm.gat
1 correct nm.gat [nm.gat]
string to test (hit <Enter> to end)> n%m.gat
0 Invalid n%m.gat [n%m.gat]
string to test (hit <Enter> to end)>
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

6211 次

最近记录:

8 年,5 月 前