批量。获取子字符串

问题描述 投票:1回答:1

是的我知道 - 网上有很多信息。但。让我们试试他们写的东西。

不幸的是,这不起作用,因为:〜语法期望值不是变量。要解决这个问题,请使用CALL命令,如下所示:

SET _startchar=2
SET _length=1
SET _donor=884777
CALL SET _substring=%%_donor:~%_startchar%,%_length%%%
ECHO (%_substring%)

Ok. My Example.

请告诉我 - 我做错了什么?

batch-file cmd
1个回答
1
投票

1)你可以试试delayed expansion

@Echo off

setlocal enableDelayedExpansion

SET _startchar=2
SET _length=1
SET _donor=884777
SET _substring=!_donor:~%_startchar%,%_length%!
ECHO (%_substring%)

2)使它与CALL SET一起使用你需要双%(但它会比第一种方法慢):

@Echo off

::setlocal enableDelayedExpansion

SET _startchar=2
SET _length=1
SET _donor=884777
call SET _substring=%%_donor:~%_startchar%,%_length%%%
ECHO (%_substring%)

3)您可以使用延迟扩展和循环。如果有嵌套的括号块并且在那里定义了_startchar和_length,它会很有用。它会比CALL SET更快:

@Echo off

setlocal enableDelayedExpansion

SET _startchar=2
SET _length=1
SET _donor=884777


for /f "tokens=1,2 delims=#" %%a in ("%_startchar%#%_length%") do (
    SET _substring=!_donor:~%%a,%%b!
)

ECHO (%_substring%)

4)您可以使用子程序和延迟扩展:

@Echo off

setlocal enableDelayedExpansion

SET _startchar=2
SET _length=1
SET _donor=884777


call :subString %_donor% %_startchar% %_length% result
echo (%result%)

exit /b %errorlevel%

:subString %1 - the string , %2 - startChar , %3 - length , %4 - returnValue
setlocal enableDelayedExpansion
set "string=%~1"
set res=!string:~%~2,%~3!

endlocal & set "%4=%res%"

exit /b %errorlevel%
© www.soinside.com 2019 - 2024. All rights reserved.