batch-file - 检查字符串是否被引用并向字符串添加引号的问题

标签 batch-file cmd escaping quotes

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

代码

@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
)

这是我得到的输出
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.

更新

我现在意识到我不能使用 AND。但即使我删除我也有问题。

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

我得到
The syntax of the command is incorrect.

最佳答案

@echo off
setlocal EnableDelayedExpansion

set mystring=Non quoted string
echo %mystring%
if !mystring:~0^,1!!mystring:~-1! equ "" (
   echo -^> String is quoted
) else (
   echo -^> String not quoted
   set newstring="%mystring%"
   echo New string: !newstring!
)
echo/

set mystring="My quoted string"
echo %mystring%
if !mystring:~0^,1!!mystring:~-1! equ "" (
   echo -^> String is quoted
) else (
   echo -^> String not quoted
   set newstring="%mystring%"
   echo New string: !newstring!
)

关于batch-file - 检查字符串是否被引用并向字符串添加引号的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31358869/

相关文章:

windows - SSH 和 SCP 失败,错误为 "CreateProcessW failed error:2 posix_spawn: No such file or directory"

perl\@转义序列

c++ - CMake:生成批处理文件调用 cl.exe

windows - (脚本)使用PowerShell或cmd的Windows最新Git?

php - 为什么 PHP 执行时会出现 'node' ' 无法识别为内部或外部命令、可运行程序或批处理文件?

c# - C#中的批处理文件执行

Windows 批处理文件 : . bat vs .cmd?

batch-file - HTA 和批处理混合,从 BATCH 部分传递变量

C# 和 JavaScript - 转义单引号字符

SQLite3 : Insert BLOB with NULL characters in C++