你好,我正在努力弄清楚如何在批处理文件中获取字符串变量的结束字符。 我可以使用 SET subStr=!sub:~1,1! 轻松获取第一个字符,但我真正想做的是查找字符串是否包含 ~ 所以我尝试了几个例子,但因为我在 for 循环中这样做,它更具挑战性。我有一个函数来获取字符串长度,它工作正常,但我只是不知道如何使用子命令 I.E.
FOR /F %%i IN ('DIR /b "%protoDir%" *.proto 2^>NUL') DO (
:: Check and ignore tilde temp files which start or ends with ~
SET sub=%%i
call :strLen sub str
ECHO strLength=!str!
SET /A len=!str!-1
ECHO length - 1 = !len!
SET subStr2="!sub:~!len!,!len!!" <-- ERROR IS HERE
ECHO !subStr2!
SET subStr=!sub:~1,1!
IF NOT !subStr! == ~ (
IF NOT !subStr2! == ~ ( SOME CODE HERE... )
)
)
:: Function to get a strings length
:strLen
setlocal enabledelayedexpansion
:strLen_Loop
if not "!%1:~%len%!"=="" set /A len+=1 & goto :strLen_Loop
(endlocal & set %2=%len%)
goto :eof
输出是:
strLength=26
长度 - 1 = 25
“ReceiverDiagnostics.proto lenlen”应该是 ~
我更愿意使用下面的代码,它要简单得多,但即使使用 !,我也无法在 for 循环内工作。
IF NOT "%foobar%"=="%foobar:~=%" ( ECHO string contains ~ )
最佳答案
是的,确实不能使用表达式 !sub:~=!
,因为这与 sub-string expansion syntax 冲突(例如,!sub:~1,1!
)和 sub-string substitution syntax (例如,!sub:search=replace!
)。
但是,您可以使用以下子字符串替换功能的特例 !sub:*search=replace!
,它替换所有内容,包括第一次出现的 search
替换为 ,因为搜索字符串可以以
~
开头:
if not "!sub!"=="!sub:*~=!" echo String contains '~'.
关于windows - 批处理文件在for循环中获取开始和结束字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59181487/