这是一个使用!
DelayedExpansion 方法的示例。
@echo off
setlocal EnableExtensions EnableDelayedExpansion
set "xxString=All your base are belong to us"
set "xxSubString=your base are belong"
set "xxNewSubString=of your bases belong"
echo Before
set xx
echo.
set "xxString=!xxString:%xxSubString%=%xxNewSubString%!"
echo After
set xx
endlocal
pause >nul
输出
Before
xxNewSubString=of your bases belong
xxString=All your base are belong to us
xxSubString=your base are belong
After
xxNewSubString=of your bases belong
xxString=All of your bases belong to us
xxSubString=your base are belong
固定你的
@echo off
:: Make sure that you have delayed expansion enabled.
setlocal EnableDelayedExpansion
:modifyString what with [in]
SET "_what=%~1"
SET "_with=%~2"
SET "_In=%~3"
ECHO "%_what%"
ECHO "%_with%"
ECHO "%_In%"
:: The variable names were not the same as the ones
:: defined above.
SET _In=!_In:%_what%=%_with%!
ECHO %_In%
:: This will not change the value of the 3rd parameter
:: but instead will create a new parameter with the
:: value of %3 as the variable name.
SET "%~3=%_In%"
endlocal
EXIT /B
如何在不延迟扩展的情况下进行子字符串替换。使用该call
命令创建两个级别的变量扩展。使用单%
环绕变量首先展开,然后使用双%%
环绕变量展开第二次。
@echo off
setlocal EnableExtensions
set "xxString=All your base are belong to us"
set "xxSubString=your base are belong"
set "xxNewSubString=of your bases belong"
echo Before
set xx
echo.
call set "xxString=%%xxString:%xxSubString%=%xxNewSubString%%%"
echo After
set xx
endlocal
pause >nul