我为什么不能得到延迟扩展变量的子字符串中的if语句? [英] Why can I not get a substring of a delayed expansion variable in an if statement?

查看:96
本文介绍了我为什么不能得到延迟扩展变量的子字符串中的if语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么字符串处理工作内嵌在if语句中不使用延迟扩展变量 - 但除此之外失败。例如:

Why does string-manipulation work inline in an if statement without using delayed expansion variables - but fails otherwise. For example:

set test=testString
if %test:~0,4%==test echo Success

这正常工作;返回成功。但是如果我做到以下几点:

This works correctly; returning Success. However if I do the following:

setLocal enableDelayedExpansion
set test=testString
if !test:~0,4!==test echo Success

我收到错误! - 4 ==测试是意外,此时

显然,你可以做这样的事情来解决这个设置补偿=测试!〜0,4 然后只需使用补偿!!! if语句变量。

Obviously you can get around this by doing something like set comp=!test:~0,4! then just using the !comp! variable in the if statement.

推荐答案

npocmaka正确诊断的IF命令都有自己特殊的分析阶段的问题,而变量扩展中令牌的分隔符导致问题。

npocmaka correctly diagnosed the problem that the IF command gets its own special parsing phase, and token delimiters within the variable expansion are causing problems.

换人也导致了一个问题:

Substitution also causes a problem:

:: This fails
if !test:String=!==test echo Success

您不需要任何扩充看问题。

You don't need any expansion to see the problem.

:: This fails
if not a;b==a echo OK

为什么正常扩建工程的原因是因为,经过的中频解析之前发生,但发生延迟扩展的如果解析。

The reason why normal expansion works is because that occurs before the IF parsing, but delayed expansion occurs after IF parsing.

使用引号的替代方法是逃避问题的字符。

An alternative to using quotes is to escape the problem characters.

:: Both of these work
if !test:~0^,4!==test echo Success
if !test:String^=!==test echo Success

这篇关于我为什么不能得到延迟扩展变量的子字符串中的if语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆