Batch - get string between first and last double quotes
This will work reliably if the string contains no unquoted special characters such as &
|
>
<
^
@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
This solution has two parts, as in one line of code.
1) Remove all characters with the first one "
.
This part uses the documented find and replace feature of variable expansion with an asterisk in front of the search string. The following is an excerpt from help obtained by typing HELP SET
or SET /?
from the command line.
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 "
and trim the string at that point.
The complete SET assignment expression can be enclosed in quotation marks, and the closing quotation marks will be discarded, and all text after the last comment will be ignored. In the description below, the variable var
will define the value 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 don't know of any official documentation for this feature, but it is an essential tool for developing batch files.
This process occurs after the completion of the expansion from Part 1. Thus, SET truncates on the last entry "
in the expanded value.
source to share