簡體   English   中英

如何檢查變量是否在批處理文件中包含特殊字符

[英]how to check if the variable contains special characters in batch file

如何檢查批處理文件中的變量是否包含特殊字符? 例如,如果我的變量包含文件名,則該文件名不應包含\\/ < > | : * " ?等字符\\/ < > | : * " ? \\/ < > | : * " ?這些。

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

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

:next
echo correct

我使用此鏈接作為參考正則表達式來驗證文件夾名稱和文件名

您不能使用echo %param%| findstr /r ... echo %param%| findstr /r ...甚至沒有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

.*[<>:\\"\\"/\\\\|?*%%].*正則表達式說明

  • .* -字符串前面出現零個或多個字符;
  • [<>:\\"\\"/\\\\|?*%%]保留字符集中的任何一個字符:
    • < (小於);
    • > (大於);
    • :冒號);
    • " (雙引號)轉義為\\"\\" (findstr和批處理解析器);
    • / (正斜杠);
    • \\ (反斜杠)轉義為\\\\ (findstr);
    • | (垂直條或管);
    • ? (問號);
    • * (星號);
    • % (百分號)轉為%% (對於批處理解析器); 實際上, %不是為NTFS文件系統保留的,而是需要在純cmd和/或批處理腳本中進行特殊轉義;
  • .* -字符串末尾出現零個或多個字符。

這里有一些關於SO問題的鏈接,其中包括Aacini,DBenham,Jeb(以及其他人)的詳盡解答。 令人興奮,令人着迷的閱讀...

並詳細介紹David 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)>

您可以將findstr行更改為

set "param=Test < string"

cmd /v:on /c echo(^^!param^^! | findstr /r "^[^\\/?%%*:|<>\.\"]*$^" > nul

if %errorlevel% equ 0 ( 
echo OK
) ELSE (
  echo Invalid, special character found
)

這是可行的,因為參數將在子cmd.exe進程中擴展,並且延遲擴展。
是否啟用延遲擴展並不重要,該行始終有效。
我更改了正則表達式,因為搜索報價本身有點令人討厭。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM