If String is Enclosed in Quotes Do Commands

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
alleypuppy
Posts: 82
Joined: 24 Apr 2011 19:20

If String is Enclosed in Quotes Do Commands

#1 Post by alleypuppy » 25 Nov 2011 11:14

Hello,

I know this is probably possible, but I don't know how to do it. I want to create an IF statement that checks if a predefined variable is enclosed in quotes, and if it is, do certain commands. My guess is that I have to use some sort of string manipulation, but I'm not entirely sure how to do it.

Thanks in advance!

paultomasi
Posts: 25
Joined: 24 Feb 2009 14:52
Location: UK
Contact:

Re: If String is Enclosed in Quotes Do Commands

#2 Post by paultomasi » 25 Nov 2011 12:38

Try the following:

Code: Select all

if [%var%]==["%var:"=%"] (
   rem var enclosed in quotes
) else (
   rem var not enclosed in quotes
)

alleypuppy
Posts: 82
Joined: 24 Apr 2011 19:20

Re: If String is Enclosed in Quotes Do Commands

#3 Post by alleypuppy » 25 Nov 2011 13:13

paultomasi wrote:Try the following:

Code: Select all

if [%var%]==["%var:"=%"] (
   rem var enclosed in quotes
) else (
   rem var not enclosed in quotes
)
When I executed the statement with this syntax, it came up with an error, but I was able to manipulate it to make it work. Here's what I did:

Code: Select all

IF /I [%var:~1,-1%]==[%var:"=%] (commands)
Thanks!

paultomasi
Posts: 25
Joined: 24 Feb 2009 14:52
Location: UK
Contact:

Re: If String is Enclosed in Quotes Do Commands

#4 Post by paultomasi » 25 Nov 2011 14:18

Yeah, the '/I' is good when you can ignore case.

A better way to do it is like this:

Code: Select all

if [^%var:~0,1%]==[^"] (
  if [^%var:~-1,1%]==[^"] (
     rem first and last character are quotes
  )
)

This way, you will avoid DOS throwing up errors in certain circumstances.

paultomasi
Posts: 25
Joined: 24 Feb 2009 14:52
Location: UK
Contact:

Re: If String is Enclosed in Quotes Do Commands

#5 Post by paultomasi » 25 Nov 2011 14:48

Of course, it goes without saying:

- var should be defined
otherwise you get an error

- var should be at least 2 characters wide
otherwise ^%var:~0,1% is the same character as ^%var:~-1,1%

alleypuppy
Posts: 82
Joined: 24 Apr 2011 19:20

Re: If String is Enclosed in Quotes Do Commands

#6 Post by alleypuppy » 26 Nov 2011 10:53

paultomasi wrote:Yeah, the '/I' is good when you can ignore case.

A better way to do it is like this:

Code: Select all

if [^%var:~0,1%]==[^"] (
  if [^%var:~-1,1%]==[^"] (
     rem first and last character are quotes
  )
)

This way, you will avoid DOS throwing up errors in certain circumstances.
Okay I will use this instead. This is what I was originally thinking about doing (having the first and last character equal a quotation mark), but I wasn't sure how to do it. I didn't know you have to escape the variable itself as well as the quotation mark. Thanks a lot!

Post Reply