1.

Solve : Check if a variable starts with a quote character?

Answer»

I need to have a batch file that checks if a variable has a quote character for the first character. I have tried this:
set fname=%1
set bQuote=0
if %fname:~0,1% == ^" (
set bQuote=1
)

When I run this, I get an ERROR '( was unexpected at this time.' I assume it's because the quote character isn't escaped properly. When there is a quote character, the line reads: if " == ^", which leaves the first quote as 'open'. Without the ^ doesn't work either.

Any ideas?What is the purpose (briefly)? Is the problem that the variable could be either unquoted, or quoted at both beginning and END, or liable to just have a leading quote?

You do know about the tilde (~) MODIFIER, which strips leading and/or surrounding quotes (if PRESENT)? It does NOTHING if there are no quotes.

i.e. if %1 is "hello world", or "hello world then %~1 becomes hello world, but if %1 is hello world then %~1 is also hello world





Any other language, a regular expression (RegEx) would be the way to go. In batch, delayed expansion should help out:

Code: [Select]@echo off
setlocal enabledelayedexpansion

set fname=%1
set quote="
set bquote=0

if "!fname:~0,1!" EQU "!quote!" (
set bquote=1
)

Good luck Thank you all. I think I've got it solved.Quote from: Sidewinder on February 05, 2014, 07:53:55 AM

Any other language, a regular expression (RegEx) would be the way to go.
there are helper methods to check for strings. Some language like Perl and Java have index(), some have contains(). In Python its simple as "if '"' in string" . Vbscript has InStr


Discussion

No Comment Found