問題:如何比較用戶輸入的包含特殊字符的字串,例如7^7%7&7=7"7!7在 Windows Batch 中?
未完成的代碼:
set/p str1=URL:
rem if %str1%==7^7%7&7=7"7!7 ( // syntax error
rem if "%str1%"=="7^^7%%7^&7=7^"7!7" ( // still syntax error
echo Nice
) else (
echo Bad
)
期望輸出:
> URL: 7^7%7&7=7"7!7
> Nice
> URL: 42
> Bad
ps用戶輸入的字串在實際情況下實際上是有效的 url,因此所有有效的 url 字符都可以輸入,包括引號以用于與此問題類似的更一般情況。
uj5u.com熱心網友回復:
主要問題是不平衡的報價。條件:
if "%str1%"=="7^7%%7&7=7"7!7^" (
echo Nice
) else (
echo Bad
)
只要變數本身不包含(不平衡的)引號,就不應再自行回傳語法錯誤(假設延遲變數擴展被禁用)str1。如您所見,%-symbol 必須加倍,獨立于引號,但其他特殊字符只有在出現在引號之外時才必須轉義。最后一個引號被轉義,所以它不被識別。
但是,如果您7^7%7&7=7"7!7因為 中的引號而進入提示,這仍然會失敗str1,因為(立即)變數擴展發生在檢測到特殊字符之前。防止條件失敗的唯一方法,獨立于用戶輸入,必須使用延遲變數擴展:
set /P str1="URL: "
rem // At first, enable delayed variable expansion:
setlocal EnableDelayedExpansion
rem /* Then apply it by enclosing variables with `!!` rather than `%%`;
rem there are now even more complex escape sequences necessary though: */
if "!str1!"=="7^^7%%7&7=7"7^^!7^" (
echo Nice
) else (
echo Bad
)
endlocal
您可能已經意識到,比較的正確運算式現在看起來很奇怪,因為延遲擴展可能需要一些額外的轉義,具體取決于運算式是否包含感嘆號。
為了避免需要這種相當混亂和難以辨認的轉義運算式,首先將比較字串分配給一個變數,同時延遲擴展仍然被禁用:
set /P str1="URL: "
rem /* Predefine comparison expression; you always have to double `%`-symbols,
rem and you still need to escape some special characters that appear unquoted,
rem but escaping sequences do not depend on whether or not there is a `!`: */
set "cmp1=7^7%%7&7=7"7!7^"
rem // At first, enable delayed variable expansion:
setlocal EnableDelayedExpansion
rem // Then apply it by enclosing variables with `!!` rather than `%%`:
if "!str1!"=="!cmp1!" (
echo Nice
) else (
echo Bad
)
endlocal
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/387540.html
上一篇:如何讓VisualStudio2015與AzureDevOpsGit存盤庫一起使用
下一篇:Python函式中的計數變數
