Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
625 views
in Technique[技术] by (71.8m points)

batch file - Problems checking if string is quoted and adding quotes to string

I am trying to check if a string is quoted by checking the first and last characters of the string. But my script fails when checking for the quote see output: AND was unexpected at this time. below.

Code

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

This is the output I am getting

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.

UPDATE

I realise now I cannot use AND. But even if I remove I have a problem.

eg

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

I get

The syntax of the command is incorrect.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I corrected the syntax error you got. It was probably because of wrong escape sequence. You should've used "" instead of ^" due to this documentation. But it didn't work for me too, it's little tricky to deal with double quotes.

Personally, I replace " with + or some other character before manipulating a string. So this piece of code works fine:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...