windowsif-statementbatch-filespecial-charactersvariable-expansion

"if contains" with forbidden special characters


I'm making a YouTube downloader. A bug has come up with playlists and I want it to check if the inputed link is a playlist. This is done by checking for the presence of list. So, I copied my normal if statement and ran it, but it didn't like this:

if "%link:list=%" == "%link%" goto Playlist

I think the three special characters affecting it that are used in Youtube Playlist links are ? and & and =

ChatGPT kept trying to use either of the first two examples below. The first one I can't use as I rely on %ERRORLEVEL, and log the errors. The second one gave the same error codes as my original attempt.

First version:

echo %link%| findstr /C:"list=" >nul 2>&1
if %ERRORLEVEL% equ 0 goto Playlist

Second version:

if not x%test_link:list=%==x%link% goto Playlist

This third version made me give up on ChatGPT, so now I'm here!

REM Check if 'list=' is part of the string 
for /F "tokens=1,2 delims=&" %%A in ("%test_link%") do (
    if "%%B" neq "" (
        if "%%A" neq "%%Alist=" (
            set "playlist=1"
        )
    )
)

Solution

  • you were close with your first approach, you just got the logic a little wrong. the substition removes list if it is present in the variable link, meaning the condition will not be true if the string list is present. therefore:

    If defined link If /i Not "%link:list=%" == "%link%" goto:Playlist Would be the correct logic. To safely expand user input, it is advisable to perform such comparisons with Setlocal enabledelayedexpansion active and using: If defined link If /i Not "!link:list=!" == "!link!" goto:Playlist