我正在尝试批量创建一个字符串,在字符串中找到一个字符串并用第三个字符串替换它。
在搜索时,我发现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]
。
任何提示?
答案 0 :(得分:3)
以下是使用!
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
答案 1 :(得分:1)
谢谢大家!
我粘贴你最终制作的东西:
:modifyString what with in tRtn
set "_in=%~3"
set "_in=!_in:%~1=%~2!"
IF NOT "%~4" == "" SET %~4=%_in%
EXIT /B
E.G。如果我这样称呼这个子:
SET "str=All your base are belong to us"
SET "toFind=your base are belong"
SET "space=of your bases belong"
ECHO %str%
CALL :modifyString "%toFind%" "%space%" "%str%" string
%string%将成为新的更正字符串,所以如果你这样做......
ECHO "%string%"
它会打印出来:
"All of your bases belong to us"
P.S。我很抱歉,如果我迟到了,但由于我的声誉很低,我不得不等待!