[英]Batch File: Is it possible to extract a substring where the index is a variable?
如果我有两个变量, string
和index
,并且我想从索引开始提取子字符串,我可以使用SET
命令来执行此操作吗? 例如:
@ECHO off
SET string=Hello
SET index=3
ECHO %string:~%index%%
当预期结果为lo
时,此方法返回Helloindex%
。 我想做的事可能吗?
问候,
安德鲁
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET string=Hello
SET index=3
ECHO !string:~%index%!
GOTO :EOF
当然。 这是使用延迟扩展的一种方法。
您可能使用哪种方法取决于您的意图和参数。 对于众多解决方案和特殊情况,您的问题确实过于笼统。
如果在括号内使用子字符串,则可以使用它-再次比CALL
方法更快,但是有点冗长(例如,对于loop,如果条件...):
@ECHO off
set start=2
set end=5
set str=Hello World
echo %str:~2,5%
setlocal enableDelayedExpansion
for /f "tokens=1,2" %%a in ("%start% %end%") do echo !str:~%%a,%%b!
endlocal
如果您的子字符串未在方括号内提取(与magoo的答案相同):
@ECHO off
set start=2
set end=5
set str=Hello World
setlocal enableDelayedExpansion
echo %str:~2,5%
echo !str:~%start%,%end%!
endlocal
另一种方法是使用CALL
,但这要慢得多(尽管它需要更少的代码):
@ECHO off
set start=2
set end=5
set str=Hello World
echo %str:~2,5%
call echo %%str:~%start%,%end%%%
它也可以用子程序完成,但因为它也使用CALL
,它的性能不是很好:
@ECHO off
set start=2
set end=5
set str=Hello World
call :substr "%str%" %start% %end%
goto :eof
:substr
setlocal enableDelayedExpansion
set "_str=%~1"
echo !_str:~%2,%3!
rem without delayedExpansion
rem call echo %%_str:~%2,%3%%
endlocal
goto :eof
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.