JSI Tip 4191. How do I parse a string using position and length variables?


NOTE: See A better way to parse a string using position and length variables.

NOTE: See tip 9470 » A better way to determine the length of a string.

NOTE: See tip 9485 » A better way to determine the position and length of a sub-string in a string.

I first described parsing a string variable in tip 0932 » How do I parse a string?

There are a number of ways to parse a string using variable position and length, but the easiest way is to create a general purpose batch program which you call.

Create $PosLen.bat in your path. The usage syntax is:

call $PosLen String Pos Len

where Pos is the starting position, from 0, of the sub-string you wish to extract, and Len is the length of the sub-string you wish to extract. $PosLen returns the $substring environment variable containing the extracted sub-string.

$PosLen.bat contains:

@echo off
setlocal
set $substring=
if \{%1\} EQU \{\} goto end
if NOT "%3" GTR "0" goto end
set $string=####%1####
set $string=%$string:####"=%
set $string=%$string:"####=%
if "%$string%" EQU "" goto end
set $string=%$string:####=%
for /f "Tokens=*" %%i in ('@echo %%$string:~%2^,%3%%') do set $substring=%%i
:end
endlocal&set $substring=%$substring%
REM end $PosLen
NOTE: The Pos and Len arguments can be any mix of constant, string variable, or numeric variable.

Demonstration of usage:

If user Jennifer is logged on, running the following code:

@echo off
setlocal
call $poslen %UserName% 0 1
@echo %$substring%
call $poslen "%UserName%" 1 2
@echo %$substring%
set pos=2
set len=3
call $poslen "%UserName%" %pos% %len%
@echo %$substring%
set /a pos=3
set /a len=4
call $poslen "%UserName%" %pos% %len%
@echo %$substring%
endlocal

returns:

J
en
nni
nife
NOTE: See tips:

4192 » How can I determine if a string contains a specific sub-set of characters?
4193 » How can I determine the length of a string?
4194 » How do I determine the position of a sub-string in a string?



Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish