JSI Tip 4192. How can I determine if a string contains a specific sub-set of characters?


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

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

I have scripted $contains.bat to determine if a string contains a specific sub-set of characters.

$contains returns the $answer environment variable, which is set to N (sub-set not found) or Y (sub-set located).

The usage syntax is:

$contains string sub-set

where sub-set can be a constant or variable.

$contains.bat contains:

@echo off
setlocal
set $answer=N
if \{%1\} EQU \{\} goto end
if \{%1\} EQU \{""\} goto end
if \{%2\} EQU \{\} goto end
if \{%2\} EQU \{""\} goto end
set $string=####%1####
set $string=%$string:####"=%
set $string=%$string:"####=%
if "%$string%" EQU "" goto end
set $string=%$string:####=%
set $substring=####%2####
set $substring=%$substring:####"=%
set $substring=%$substring:"####=%
if "%$substring%" EQU "" goto end
set $substring=%$substring:####=%
for /f "Tokens=*" %%k in ('@echo %%$string:%$substring%^=%%') do @set $work$=%%k
if NOT "%$string%" EQU "%$work$%" set $answer=Y
:end
endlocal&set $answer=%$answer%
REM end $Contains

Demonstration of usage

Gettype will display one of the following if you are running Windows NT or Windows 2000:
\\ComputerName is a xxx installation
where xxx is one of the following:

   Windows NT Workstation 
   Windows 2000 Professional
   Windows NT Server Non-Domain Controller 
   Windows 2000 Server Non-Domain Controller 
   Windows NT Server Domain Controller 
   Windows 2000 Server Domain Controller 
   Windows NT \[Enterprise/Terminal\] Server Domain Controller 
   Windows NT \[Enterprise/Terminal\] Server Non-Domain Controller

Here is a code snippet to determine if you are logged onto windows 2000:

if "%OS%"=="Windows_NT" goto :WINNT
set $string=W9x, WMe, or ????
goto :EOF
:WINNT 
for /f "Tokens=*" %%i in ('gettype') do set $string="%%i"
call $contains %$string% 2000
if NOT "%$answer%" EQU "Y" goto :EOF
@echo %$string% 
NOTE: See tips:

4191 » How do I parse a sring using position and length variables?
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