3

Thanks to this community I have finally learned how to escape exlamation marks for immediate use in a batch delayedExpansion block. (use two escape carets not just one, awesome)

But I can't seem to find or figure out how to pass the contents of a variable containing an exclamation mark as parameter to a batch subroutine.

example:

@echo off
setLocal EnableDelayedExpansion
set variable=Hello^^!
echo "!variable!"
call :subroutine "!variable:^^!=^^!!"
pause
exit

:subroutine
echo "%~1"
exit/b

Output:

"Hello!"
"Hello"
Press any key to continue . . .

I want the second "Hello" to include an exclamation mark. I have tried various permutations of substring replacement on line 5 to no avail.

help

4

2 回答 2

2

您需要一种不同的方式来替换变量,以及更多的插入符号。

@echo off
setLocal EnableDelayedExpansion
set variable=Hello^^!
echo "!variable!"
call :subroutine %variable:!=^^^^^^^^^^!%
exit /b

:subroutine
echo %~1
exit /b

或带引号:调用 :subroutine "%variable:!=^^^!%"

在您的函数中,您需要在%1没有任何引号的情况下进行扩展,因为参数中插入符号的数量总是奇数CALL

但是,尝试这样的事情根本不是一个好主意。
我同意 Aacini 的观点,您应该改用通过引用传递。
这是处理任何可能的内容的唯一方法。

@echo off
setLocal EnableDelayedExpansion
set variable=Hello^^!
echo "!variable!"
call :subroutine variable
exit /b

:subroutine
echo !%1!
exit /b
于 2014-06-08T20:55:07.553 回答
1

也许问题不在于如何将数据传递给子程序,而在于如何获取其中的数据

@echo off

    setlocal enabledelayedexpansion

    set "var=Hello^!"

    setlocal disabledelayedexpansion
    echo %var%
    call :echo1 %var%
    call :echo2 var
    endlocal

    setlocal enabledelayedexpansion
    echo !var!
    call :echo1 !var!
    call :echo2 var
    endlocal

    endlocal
    exit /b

:echo1
    setlocal disabledelayedexpansion
    echo %~1
    endlocal
    goto :eof

:echo2
    setlocal enabledelayedexpansion
    echo !%~1!
    endlocal
    goto :eof
于 2014-06-07T20:07:33.387 回答