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.
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"
)
there is no AND in batch. Use
if var1==value1 if var2==value2 echo both ok
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With