Tran Ngu Dang
Tran Ngu Dang

Reputation: 2640

Batch - Get string between first and last double quotes

I have a string like this:

Testing:"abc"def"ghi"

I want to get: abc"def"ghi and put it into a variable, is there any possible way?

I want a general way of doing that (first and last quotes, not first and fourth quotes)

Upvotes: 3

Views: 3280

Answers (1)

dbenham
dbenham

Reputation: 130889

This will work reliably as long as the string does not contain unquoted special characters like & | > < ^

@echo off
set str=Testing:"abc"def"ghi"extra
echo str = %str%
set "new=%str:*"=%
echo new = %new%

-- OUTPUT --

str = Testing:"abc"def"ghi"extra
new = abc"def"ghi

Explanation

There are two parts to this solution, both in the same line of code.

1) Remove all characters up through the first ".

This part uses the documented search and replace feature of variable expansion, with an asterisk before the search string. The following is an excerpt from the help gotten by typing HELP SET or SET /? from the command prompt.

Environment variable substitution has been enhanced as follows:

    %PATH:str1=str2%

would expand the PATH environment variable, substituting each occurrence
of "str1" in the expanded result with "str2".  "str2" can be the empty
string to effectively delete all occurrences of "str1" from the expanded
output.  "str1" can begin with an asterisk, in which case it will match
everything from the beginning of the expanded output to the first
occurrence of the remaining portion of str1.

2) Find the last occurrence of " and truncate the string at that point.

The entire SET assignment expression can be enclosed in quotes, and the enclosing quotes will be discarded and all text after the last quote ignored. The statement below will define variable var to have a value of value.

set "var=value" this text after the last quote is ignored

If there is no last quote, then the entire remainder of the line is included in the value, possibly with hidden spaces.

set "var=This entire sentence is included in the value.

I am not aware of any official documentation for this feature, but it is an important tool for batch file development.

This process occurs after the expansion from part 1 has completed. So the the SET truncates at the last occurrence of " in the expanded value.

Upvotes: 3

Related Questions