这可能吗?
例如,假设我有一个包含以下字符串的变量:
str=This is a test - because it can be
我需要做的是能够从%str%变量中搜索并删除包括“空格,破折号,空格”在内的所有内容。所以,我最终会得到:
str=This is a test
我可以轻松地对单个字符执行此操作,删除或替换所述单个字符,但是无法弄清楚如何使用模式来实现。
先感谢
答案 0 :(得分:1)
这使用字符串替换按空格分隔字符串。它将变量的第一部分重新分配回str变量,而第二部分由于使用nul重定向而被忽略。
@echo off
set "str=This is a test - because it can be"
(set "str=%str: - =" & set /p "=%")<nul >nul
echo %str%
pause
答案 1 :(得分:1)
有很多方法可以达到相同的结果:
:: Q:\Test\2018\08\07\SO_51729389.cmd
@Echo off & setlocal
:: you should always enclose the var=content in double quotes
Set "str=This is a test - because it can be"
Echo Original [%str%]
:: method 1 shuffle: string substitution with the asterisk
Set "str2=%str:* - =%"
Call Echo method 1 [%%str: - %str2%=%%]
:: method 2 change the " - " to a single char delims and use for /F
for /f "delims=|" %%A in ("%str: - =|%") do Echo method 2 [%%A]
:: method 3 similar to Squashman's
Set "str3=%str: - ="&Set "_=%"
Echo method 3 [%str3%]
示例输出:
> Q:\Test\2018\08\07\SO_51729389.cmd
Original [This is a test - because it can be]
method 1 [This is a test]
method 2 [This is a test]
method 3 [This is a test]
答案 2 :(得分:0)
可以使用语法替换来解决问题。我建议您在这里详细了解:https://ss64.com/nt/syntax-replace.html
为解决您的问题,将格式设置为SET _result=%_test:ab=%
。这将允许您从所需的字符串中删除定义的文本。
代码:
@echo off
::Define text as string
set str=This is a test - because it can be
::Remove string
set str=%str: - because it can be=%
::Echo result
echo %str%
pause
结果:
This is a test