[英]BATCH: String substitution sub
我正在嘗試制作一個批處理子,在字符串中找到一個字符串並用第三個字符串替換它。 搜索四周,我發現在這里 ,我可以擦除與一個字符串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%
。
有小費嗎?
這是一個使用的例子!
延遲擴展方法。
@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
謝謝大家!
我貼你最后做的:
:modifyString what with in tRtn
set "_in=%~3"
set "_in=!_in:%~1=%~2!"
IF NOT "%~4" == "" SET %~4=%_in%
EXIT /B
EG如果我這樣稱呼這個子:
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"
PS我很抱歉,如果我遲到了,但由於我的低聲譽,我不得不等待!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.