Andrew
Andrew

Reputation: 293

Batch File: Is it possible to extract a substring where the index is a variable?

If I have two variables, string and index, and I want to extract a substring starting from the index, can I use the SET command to do this? For example:

@ECHO off
SET string=Hello
SET index=3
ECHO %string:~%index%%

This returns Helloindex% when expected result is lo. Is what I am trying to do possible?

Regards,

Andrew

Upvotes: 2

Views: 7739

Answers (2)

npocmaka
npocmaka

Reputation: 57252

In case of substringing within brackets you can use this - again faster than CALL approach but is a little bit verbose (e.g. for loop , if conditions...):

@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

In case your substring is not extracted within brackets (same as magoo's answer):

@ECHO off

set start=2
set end=5
set str=Hello World

setlocal enableDelayedExpansion
echo %str:~2,5%
echo !str:~%start%,%end%!
endlocal

another way is to use CALL , but this is much slower (despite it requires less code):

@ECHO off

set start=2
set end=5
set str=Hello World

echo %str:~2,5%
call echo %%str:~%start%,%end%%%

It can be done also with a subroutine but as it also uses CALL and it's not very performant way:

@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

Upvotes: 2

Magoo
Magoo

Reputation: 80033

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET string=Hello
SET index=3
ECHO !string:~%index%!
GOTO :EOF

Certainly. Here's one way, using delayedexpansion.

Which method you might use depends on quite what your intentions and parameters are. Your question is really too general for the multitude of solutions and special cases.

Upvotes: 5

Related Questions