我正在尝试批量制作一个子程序,在字符串中查找一个字符串并将其替换为第三个字符串。
四处寻找,我发现here我可以使用 SET
命令删除字符串。
所以,这就是我尝试过的:
:modifyString what with [in]
SET _what=%~1
ECHO "%_what%"
SET "_with=%~2
ECHO "%toWith%"
SET _In=%~3
ECHO "%_In%"
SET _In=%_In:%toWhat%=%toWith%%
ECHO %_In%
SET "%~3=%_In%"
EXIT /B
ECHO
仅用于“调试”目的。
据我所知,错误在于...
SET _In=%_In:%toWhat%=%toWith%%
...因为 % 字符关闭了 %_in%
变量。
我也尝试过诸如...
SET _In=%_In:!toWhat!=!toWith!%
SET _In=!_In:%toWhat%=%toWith%!
...以及其他没有意义的人。
这是主要问题,另一个是在[in]
中返回%_In%
。
有什么建议吗?
最佳答案
这是使用 !
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
关于string - 批处理 : String substitution sub,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14662971/