Pass, escape and recognize Special Character in Windows Batch File

前端 未结 2 1940
小鲜肉
小鲜肉 2021-01-21 19:30

I wrote a script which goes through each character of an input string and depending on the character I need to do different things. This works quite well as long as my input doe

相关标签:
2条回答
  • 2021-01-21 20:22
    @echo off
        setlocal enableextensions disabledelayedexpansion
    
        rem Value to test
        set "myText=1 <> () & !"" "
    
    :loop    
        rem Quote it to avoid problems with special characters.
        rem Closing quote is not included in value
        SET "char=%mytext:~0,1%"
    
        rem Test if we have something to test
        if not defined char goto :done
    
        rem Test first problematic characters that need escape
        if ^%char%==^" echo quote           & goto :next
        if ^%char%==^& echo ampersand       & goto :next
        if ^%char%==^> echo greater than    & goto :next
        if ^%char%==^< echo lower than      & goto :next
        if ^%char%==^^ echo caret           & goto :next
        if ^%char%==^( echo open bracket    & goto :next
        if ^%char%==^) echo close bracket   & goto :next
    
        %= ... =%
    
        rem Test for spaces 
        if "%char%"==" " echo space         & goto :next
    
        rem Test the rest of the options
        if %char%==1 echo one               & goto :next
        if %char%==! echo exclamation       & goto :next
    
        %= ... =%
    
        rem Once done, go to next character
    
    :next
        set "myText=%myText:~1%"
        if defined myText goto :loop
    
    :done
        exit /b
    
    0 讨论(0)
  • 2021-01-21 20:24

    You need to make sure there is clearly something to evaluate, even when there is nothing or only white-space to evaluate, so try this:

    if [%char%]==[] (...do something...)
    if [%char%]==[0] (...do something...)
    if [%char%]==[1] (...do something...)
    etc...
    
    0 讨论(0)
提交回复
热议问题