当左手侧为双引号时,如何在批处理脚本中比较字符

发布于 2025-02-09 21:37:20 字数 414 浏览 1 评论 0原文

我有Windows批处理代码,我正在尝试测试Value的第一个字符是否是连字符,但是当Value的第一个字符是双引号时,代码会失败。 (值来自真实代码的其他位置。)

set value=""This is a test""
set arg="%value%"
set prefix=%arg:~1,1%
if "%prefix%" == "-" ...

评估

如果“”“ = =” - “

,并且生成命令的语法不正确。我尝试插入脑图进入平等检查的两侧

if "^%prefix%" == "^-" ...

,但会产生相同的错误

if "^"" == "^-"

I have Windows Batch code where I'm trying to test if the first character of value is a hyphen but the code fails when the first character of value is a double quote. (value is coming from elsewhere in the real code.)

set value=""This is a test""
set arg="%value%"
set prefix=%arg:~1,1%
if "%prefix%" == "-" ...

Evaluates to

if """ == "-"

and generates The syntax of the command is incorrect. I tried inserting a caret into both sides of the equality check

if "^%prefix%" == "^-" ...

but that generates the same error with

if "^"" == "^-"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

装纯掩盖桑 2025-02-16 21:37:20

您可以使用Caret逃避单个角色,例如

if ^"^%prefix%^" == "-" ...

诀窍是逃避报价,否则内在的商人没有特殊的含义。

这不能适用于一个以上的字符,但是您可以切换到简单的延迟扩展。它的扩展总是安全的。

setlocal EnableDelayedExpansion
set "value="This is a test""
set "arg=!value!"
set "prefix=!arg:~1,1!"
if "!prefix!" == "-" ...

You can use the caret to escape a single character, like

if ^"^%prefix%^" == "-" ...

The trick is to escape the quotes, too, else the inner caret has no special meaning.

This can't work for more than one character, but you could switch to the even simple delayed expansion. It's expansion is always safe.

setlocal EnableDelayedExpansion
set "value="This is a test""
set "arg=!value!"
set "prefix=!arg:~1,1!"
if "!prefix!" == "-" ...
脱离于你 2025-02-16 21:37:20

测试值的第一个字符是否是连字符

另一种方法(使用原始字符串,没有其他变量):

@echo off
setlocal EnableDelayedExpansion

set value1=-correct
set value2=xfail
set value3="fail
set value
echo ---------
echo !value1!|findstr /bc:"-" >nul && echo hyphen || echo something else
echo !value2!|findstr /bc:"-" >nul && echo hyphen || echo something else
echo !value3!|findstr /bc:"-" >nul && echo hyphen || echo something else

test if the first character of value is a hyphen

Another approach (using the original string, no additional variables):

@echo off
setlocal EnableDelayedExpansion

set value1=-correct
set value2=xfail
set value3="fail
set value
echo ---------
echo !value1!|findstr /bc:"-" >nul && echo hyphen || echo something else
echo !value2!|findstr /bc:"-" >nul && echo hyphen || echo something else
echo !value3!|findstr /bc:"-" >nul && echo hyphen || echo something else
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文