Skip navigation

JSI Tip 9550. A better way to parse a string using position and length variables.


I first described how to parse a string using position and length variables in tip 4191.

I have scripted PosLen.bat to parse a string using position and length variables.

The syntax for using PosLen.bat is:

call PosLen String Pos Len SubStr

Where:

String is the string you wish to parse.

Pos    is the position in String to begin the parsing. The range is 1 - length of String.

Len    is the length of the sub-string you wish to extract. The range is 1 - length of  String.

SubStr is a call directed environment variable that will contain the sub-string.
Example:

To extract Server from a string that contains Windows Server 2003:

call PosLen "Windows Server 2003" 9 6 Answer

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.

PosLen.bat contains:

@echo off
if \{%4\}==\{\} @echo Syntax: PosLen String Pos Len SubStr&goto :EOF
if exist "%TEMP%\PosLen.vbs" goto :parse
@echo set objArgs = WScript.Arguments>"%TEMP%\PosLen.vbs"
@echo Wscript.Echo Mid(objArgs(0), objArgs(1), objArgs(2))>>"%TEMP%\PosLen.vbs"
:parse
for /f "Tokens=*" %%a in ('cscript //nologo "%TEMP%\PosLen.vbs" %1 %2 %3') do ( 
 set %4=%%a
)



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