I am trying to come up with a method of extracting 4 characters that occur after a substring match in a string. The closest thing I could come up with is terribly inefficient looking and doesn’t even work all that well. Does anyone know a better way of doing this?
@echo off
cls
SET "_TMPVAR=Ports|http:8000|https:8443|"
SET _TMPVAR=%_TMPVAR:|=,%
FOR /F "tokens=1-3 delims=," %%m in ("%_TMPVAR%") do (
SET "_TMPVAR1=%%n"
SET "_TMPVAR2=%%o"
)
SET _HTTPS=0000
IF "%_TMPVAR1:~4,1%"=="s" (
SET "_HTTPS=%_TMPVAR1:~-4%"
)
IF "%_TMPVAR2:~4,1%"=="s" (
SET "_HTTPS=%_TMPVAR2:~-4%"
)
SET _
ECHO SSL Port is %_HTTPS%
pause
One way to improve it is to eliminate the seemingly unnecessary comma replacement:
Further, you can take advantage of the delimiter list to split on
|and:to break up your schemes and ports, allowing you to put the logic inside theFORstatement:An advantage of using the delimiter behavior is that it allows for port numbers of any length.