Windows 在批处理脚本中通过匹配索引获取子字符串的位置

Windows 在批处理脚本中通过匹配索引获取子字符串的位置,windows,batch-file,substring,Windows,Batch File,Substring,我想通过匹配索引找到子字符串的位置。准确地说,假设一个字符串中有6个匹配项,我想要匹配项编号4的位置。例如: set "myString=barbarbarfoobarfoobarbar" set "myMatch=bar" set myMatchIndex=4 ... do stuff ... echo Position is: %position% Position is: 13 以下操作将产生所需的结果 不适用于特殊字符,如(!)和(“),请确保正确清理输入 :indexOf se

我想通过匹配索引找到子字符串的位置。准确地说,假设一个字符串中有6个匹配项,我想要匹配项编号4的位置。例如:

set "myString=barbarbarfoobarfoobarbar"
set "myMatch=bar"
set myMatchIndex=4
... do stuff ...
echo Position is: %position%


Position is: 13


以下操作将产生所需的结果

不适用于特殊字符,如(!)和(“),请确保正确清理输入

:indexOf
setlocal ENABLEDELAYEDEXPANSION
set indexOf_StringPosition=0
set "indexOf_Var1=%~1"
set "indexOf_Var2=%~2"
set indexOf_Var3=%3

:indexOf_NoInitLabel
set indexOf_CurrentPosition=0
set "indexOf_StringTemp=!indexOf_Var1:*%indexOf_Var2%=!"
if "%indexOf_StringTemp%"=="%indexOf_Var1%" (
    set indexOf_StringPosition=-1
    goto :indexOf_BreakLabel
)
set "indexOf_StringTemp2=!indexOf_Var1:%indexOf_Var2%%indexOf_StringTemp%=!"
if "%indexOf_StringTemp2%"=="" (
    set /a indexOf_CurrentPosition+=1
    goto :indexOf_BreakLabel
)

:indexOf_LoopLabel
if "!indexOf_StringTemp2:~%indexOf_CurrentPosition%,1!"=="" (
    set /a indexOf_CurrentPosition+=1
    goto :indexOf_BreakLabel
)
set /a indexOf_CurrentPosition+=1
goto :indexOf_LoopLabel

:indexOf_BreakLabel
set /a indexOf_StringPosition+=%indexOf_CurrentPosition%
set /a indexOf_Var3-=1
set "indexOf_Var1=!indexOf_Var1:~%indexOf_CurrentPosition%!"
if "indexOf_Var1"=="" (
    goto :indexOf_EndLabel
)
if "%indexOf_Var3%"=="0" (
    goto :indexOf_EndLabel
)
goto :indexOf_NoInitLabel

:indexOf_EndLabel
(endlocal & set %4=%indexOf_StringPosition%)
goto :eof
indexOf可以这样调用:

@echo off

set "myString=barbarbarfoobarfoobarbar"
set "myMatch=bar"
set myMatchIndex=4
call :indexOf "%myString%" "%myMatch%" %myMatchIndex% position
echo Position is: %position%
pause


rem Position is: 13


重要提示:算法的索引从1开始。这意味着“b”被视为1,“a”被视为2,依此类推。要从0开始索引,请在
之后添加以下内容:indexOf_EndLabel

if not %indexOf_StringPosition%==-1 set /a indexOf_StringPosition-=1