批处理文件中的子串帮助

时间:2016-08-06 08:17:43

标签: batch-file

如何在incno和下面的示例批次中的空间ie12345678之间提取所有内容并将其放入incno变量?

@echo off  
Set mystring=test incno12345678 wo5555 locFred Street   
Echo "my string=%mystring%"   
Echo incno   
Echo wo    
Echo loc  

incno的长度可以是8到11位,但总是在incno和字符串中的空格之间

我现在无法将%% d变量分配给mystring变量,现在它在for循环中。谁能帮我这个?见下文。

@echo off
SETLOCAL enableDelayedExpansion
color 0B
For /d %%d in ("C:\Users\%Username%\LocalData\*") do (
Echo "Folder = %%d"
Set mystring=%%d
echo "MyString = %mystring%"
pause
REM delete until (including) "incno":
set mystring=%mystring:*incno=%
echo %mystring%
REM delete starting with (including) " ":
set mystring=%mystring: =&rem %
echo "Incident Number = %mystring%"
pause
)

2 个答案:

答案 0 :(得分:4)

你可以通过两个步骤替换子串来完成它:

Set mystring=test incno12345678 wo5555 locFred Street
echo %mystring%
REM delete until (including) "incno":
set mystring=%mystring:*incno=%
echo %mystring%
REM delete starting with (including) " ":
set mystring=%mystring: =&rem %
echo %mystring%

答案 1 :(得分:2)

set "mystring=test incno12345678 wo5555 locFred Street"
for /f %%V in ("%mystring:* incno=%") do set "incno=%%V"

如果mystring可能包含有毒字符加引号,则可以使用延迟扩展:

setlocal enableDelayedExpansion
set mystring=test incno12345678 wo5555 loc"4th & Main"
for /f %%V in ("!mystring:* incno=!") do set "incno=%%V"

如果结果值可能包含!(在这种情况下不是问题),则必须切换延迟扩展

setlocal disableDelayedExpansion
set mystring=test varABC!XYZ "&)^|<>"
setlocal enableDelayedExpansion
for /f %%V in ("!mystring:* var=!") do (
  endlocal
  set "var=%%V"
)