次のような文字列があります。
Testing:"abc"def"ghi"
取得したいのですabc"def"ghi
が、それを変数に入れたいのですが、可能な方法はありますか?
それを行う一般的な方法が必要です(最初と4番目の引用ではなく、最初と最後の引用)
次のような文字列があります。
Testing:"abc"def"ghi"
取得したいのですabc"def"ghi
が、それを変数に入れたいのですが、可能な方法はありますか?
それを行う一般的な方法が必要です(最初と4番目の引用ではなく、最初と最後の引用)
文字列に引用符で囲まれていない特殊文字が含まれていない限り、これは確実に機能します&
|
>
<
^
@echo off
set str=Testing:"abc"def"ghi"extra
echo str = %str%
set "new=%str:*"=%
echo new = %new%
-- 出力 --
str = Testing:"abc"def"ghi"extra
new = abc"def"ghi
説明
このソリューションには 2 つの部分があり、どちらも同じコード行にあります。
1) 最初の までのすべての文字を削除します"
。
この部分では、変数展開の文書化された検索と置換機能を使用し、検索文字列の前にアスタリスクを付けます。HELP SET
以下は、入力またはSET /?
コマンド プロンプトから得られるヘルプからの抜粋です。
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) が最後に出現する箇所を見つけて、"
その時点で文字列を切り捨てます。
SET 代入式全体を引用符で囲むことができ、囲み引用符は破棄され、最後の引用符の後のすべてのテキストは無視されます。以下のステートメントは、 variablevar
が の値を持つように定義しますvalue
。
set "var=value" this text after the last quote is ignored
最後の引用符がない場合は、行の残りの部分全体が値に含まれ、おそらく隠しスペースが含まれます。
set "var=This entire sentence is included in the value.
この機能に関する公式ドキュメントは知りませんが、バッチ ファイル開発の重要なツールです。
このプロセスは、パート 1 からの拡張が完了した後に発生します。そのため、SET"
は展開された値の最後の出現で切り捨てられます。