Batch - Set/Reset parameters calling subroutine with exclamation mark (!) and delayed expansion?

这一生的挚爱 提交于 2019-12-05 19:23:47

Change the return part of your :get_substrings function to:

...
set "return1=!string:"=""!"
set "return1=%return1:!=^^^!%"
set "return1=!return1:""="!"

set "return2=!substring:"=""!"
set "return2=%return2:!=^^^!%"
set "return2=!return2:""="!"

FOR /F "delims=" %%s IN ("!return1!") DO FOR /F "delims=" %%b IN ("!return2!") DO (
    ENDLOCAL & SET "%1=%%s" & SET "%2=%%b" & EXIT /B 0
)

But why your solution fails?
The problem is that the set "%1=%%s" is executed in a delayed expansion context, as your complete batch uses delayed expansion.
But delayed expansion is the last expansion phase of the batch parser and it's after the parameter expansion of the %%s.
Therefore the parser tries to expand your exclamation marks, when here is only one it will be removed, when there are two like in "World! wasserschutzpolizei!" it expand the variable ! wasserschutzpolizei! to it's value (in your case it seems to be empty).

The solution simply put carets in front of any exclamation mark.
But you are also using quotes in your samples it makes more things more complicated.
To avoid problems with quotes and carets it's an easy way to double all quotes, add the carets and the change the doubled quotes back to single quotes.

Is it an option for you to have delayed expansion disabled while calling the sub-routine:

@ECHO OFF
SETLOCAL ENABLEEXTENSIONS DISABLEDELAYEDEXPANSION

    CALL :get_substrings testString substr
    SETLOCAL ENABLEDELAYEDEXPANSION
    ECHO Inside 1. local:
    ECHO !testString!
    ECHO !substr!
    ENDLOCAL

    EXIT /B 0
ENDLOCAL


:get_substrings
    SETLOCAL ENABLEDELAYEDEXPANSION

    SET string="World^! wasserschutzpolizei^!"
    SET substring="Hello^!"
    ECHO Inside get_substrings:
    ECHO !string!
    ECHO !substring!

    FOR /F "delims=" %%s IN ("!string!") DO FOR /F "delims=" %%b IN ("!substring!") DO (
        ENDLOCAL & SET "%1=%%s" & SET "%2=%%b" & EXIT /B 0
    )
EXIT /B 0

This would avoid to expand the for variables %%s and %%b when delayed expansion is enabled, because this is the last step, so exclamation marks became consumed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!