gpt4 book ai didi

batch-file - 批处理 - 获取第一个和最后一个双引号之间的字符串

转载 作者:行者123 更新时间:2023-12-04 01:09:21 28 4
gpt4 key购买 nike

我有这样一个字符串:

Testing:"abc"def"ghi"

我想得到:abc"def"ghi 并把它放到一个变量中,有什么办法吗?

我想要一个通用的方法(第一个和最后一个引号,而不是第一个和第四个引号)

最佳答案

只要字符串不包含未加引号的特殊字符(如 &),这将可靠地工作| > < ^

@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

解释

这个解决方案有两个部分,都在同一行代码中。

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 赋值表达式可以用引号括起来,括起来的引号将被丢弃,最后一个引号之后的所有文本都将被忽略。下面的语句将定义变量 var的值为 value .

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

如果没有最后一个引号,则该行的整个剩余部分都包含在值中,可能带有隐藏空格。

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

我不知道此功能有任何官方文档,但它是批处理文件开发的重要工具。

此过程发生在第 1 部分的扩展完成之后。所以 SET 在最后一次出现 " 时截断在扩展值中。

关于batch-file - 批处理 - 获取第一个和最后一个双引号之间的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14658498/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com