考虑以下代码:
@echo off
chcp 65001 >NUL
rem Main thread here which shows how to change each letter to UPPERCASE: https://stackoverflow.com/questions/34713621/batch-converting-variable-to-uppercase
rem Comment here: https://stackoverflow.com/a/34734724/8262102
rem I want to use this code to replace multiple strings but I'm having difficulty
rem with getting % replaced with double % symbols.
set "str=Change %% to double %% and replace other ^(And convert brackets^)"
echo %str% (Old variable)
call :VALIDATE str
echo %str% (New variable)
pause
goto :EOF
:VALIDATE
if not defined %~1 exit /b
for %%A in ("^%^%=^%^%^%^%" "(='('" ")=')'") do (
call set %~1=%%%~1:%%~A%%
)
goto :EOF
这会将 (
替换为 '('
,)
替换为 ')'
。
我无法将 %
替换为 %%
。
我尝试使用 %%
和 ^%
来转义 %
,但此时代码中没有运气 “^%^%=^%^%^%^%”
。
我不知道如何做到这一点。
最佳答案
这对你有帮助吗?
@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
Set "str=Change %% to %%%%, and %%%% to %%%%%%%%, (and also enclose parentheses in single quotes)."
Echo %str%
Pause
SetLocal EnableDelayedExpansion
Set "str=!str:%%=%%%%!"
Set "str=!str:(='('!"
Set "str=!str:)=')'!"
EndLocal & Set "str=%str%"
Echo %str%
Pause
或者类似的:
@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
Set "str=Change %% to %%%%, and %%%% to %%%%%%%%, (and also enclose parentheses in single quotes)."
Echo %str% (Old variable)
Call :Validate str
Echo %str% (New variable)
Pause
GoTo :EOF
:Validate
If "%~1" == "" Exit /B
SetLocal EnableDelayedExpansion
Set "_=!%~1!"
Set "_=!_:%%=%%%%!"
Set "_=!_:(='('!"
Set "_=!_:)=')'!"
EndLocal & Set "%~1=%_%"
Exit /B
[编辑/]
因为……
@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
Set "str=Change %% to %%%%, and %%%% to %%%%%%%%, (and also enclose parentheses in single quotes)."
Echo %str% (Old variable)
Call :Validate str
Echo %str% (New variable)
Pause
GoTo :EOF
:Validate
If "%~1" == "" Exit /B
SetLocal EnableDelayedExpansion
Set "_=!%~1!"
For %%G In ("%%=%%%%" "(='('" ")=')'") Do Set "_=!_:%%~G!"
EndLocal & Set "%~1=%_%"
Exit /B
关于batch-file - 如何使用call命令替换for循环中的多个字符串-替换%是一个问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61990245/