JSI Tip 9485. A better way to determine the position and length of a sub-string in a string.


I have scripted String.bat to determine the position and length of a sub-string in a string.

The syntax for using String.bat is:

call String Str SubStr I|C Position Length

Where:

Str      is the string that you wish to search.

SubStr   is the sub-string that you wish to locate in Str.

I|C      is an I if you wish to ignore case, or a C is case is important.

Position is a call directed numeric environment variable that will contain a 
         0 if SubStr was NOT found, or a number representing the position of SubStr in Str.

Length   is a call directed numeric environment variable that will contain
         the length of SubStr.
NOTE: See tip 9470 » A better way to determine the length of a string.

String.bat contains:

@echo off
setlocal
if \{%5\}==\{\} goto err
set /a pos=0
set /a len=0
if exist "%TEMP%\String.vbs" goto parse
@echo dim str, substr, tb, pos>"%TEMP%\String.vbs"
@echo Set objshell = CreateObject("WScript.Shell")>>"%TEMP%\String.vbs"
@echo Set objArgs = WScript.Arguments>>"%TEMP%\String.vbs"
@echo str=objArgs(0)>>"%TEMP%\String.vbs"
@echo substr=objArgs(1)>>"%TEMP%\String.vbs"
@echo bt=objArgs(2)>>"%TEMP%\String.vbs"
@echo pos = Instr(1, str, substr, bt)>>"%TEMP%\String.vbs"
@echo Wscript.Echo pos ^& " " ^& Len(substr)>>"%TEMP%\String.vbs"
:parse
set bt=%3
if /i "%bt%" EQU "I" set bt=1&goto poslen
if /i "%bt%" NEQ "C" goto err
set bt=0
:poslen
for /f "Tokens=1,2" %%a in ('cscript.exe //nologo "%TEMP%\String.vbs" %1 %2 %bt%') do (
 set /a pos=%%a
 set /a len=%%b
)
endlocal&set /a %4=%pos%&set /a %5=%len%
goto :EOF
:err
@echo Syntax: call String Str SubStr I^|C Position Length
endlocal&set /a %4=0&set /a %5=0



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