检查字符串是否用引号并将字符串加引号时出现问题

Ang*_*ber 4 quotes cmd escaping batch-file

我试图通过检查字符串的第一个和最后一个字符来检查字符串是否被引用。但是我的脚本在检查报价时看到了失败,请参见输出:AND此时是意外的。下面。

@echo off

set mystring=Non quoted string

set myquotedstring=^"My quoted string^"

echo mystring: %mystring%

echo myquotedstring: %myquotedstring%

set result=%mystring:~0,1%

echo first character of non quoted string is: %result%

set result=%mystring:~-1%

echo last character of non quoted string is: %result%

if %mystring:~0,1%u==^" AND %mystring:~-1%==^" (
   echo this string is NOT quoted
   set newstring=^"Non quoted string^"
   echo newstring: %newstring%
)

set result=%myquotedstring:~0,1%

echo first character of quoted string is: %result%

set result=%myquotedstring:~-1%

echo last character of quoted string is: %result%

if %myquotedstring:~0,1%u==^" AND %myquotedstring:~-1%==^" (
   echo this string is quoted
)
Run Code Online (Sandbox Code Playgroud)

这是我得到的输出

mystring: Non quoted string
myquotedstring: "My quoted string"
first character of non quoted string is: N
last character of non quoted string is: g
this string is NOT quoted
newstring: "Non quoted string"
first character of quoted string is: "
last character of quoted string is: "
AND was unexpected at this time.
Run Code Online (Sandbox Code Playgroud)

更新

我知道现在我不能使用AND。但是,即使我删除我也有问题。

例如

if %mystring:~0,1%u==^" if %myquotedstring:~-1%==^" (
   echo this string is NOT quoted
   set newstring=^"Non quoted string^"
   echo newstring: %newstring%
)
Run Code Online (Sandbox Code Playgroud)

我懂了

The syntax of the command is incorrect.
Run Code Online (Sandbox Code Playgroud)

ozc*_*unc 5

我更正了您遇到的语法错误。可能是因为转义顺序错误。由于本文档""^"缘故,您应该使用而不是。但这对我也不起作用,处理双引号有点棘手。

就个人而言,在处理字符串之前,我会"+或其他字符替换。因此,这段代码可以正常工作:

set myquotedstring="My quoted string"

set firstChar=%myquotedstring:~0,1%
set lastChar=%myquotedstring:~-1%

:: Replace " with +
set firstChar=%firstChar:"=+%
set lastChar=%lastChar:"=+%

if "%firstChar%"=="+" if "%lastChar%"=="+" (
    echo "myquotedstring is quoted"
)
Run Code Online (Sandbox Code Playgroud)

  • 你的回答确实有效,这很好。Windows cmd有点麻烦! (4认同)