2016-08-06 56 views
1

如何在下面的示例批處理中提取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
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" 

如果結果值可能包含!(在這種情況下不是問題),則延遲擴展m ust被切換

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

'set mystring =%mystring:=&rem%'如何工作?我找不到記錄在任何地方? '&rem'做什麼? – DavidPostill

+0

@DavidPostill - 做紙上的替換,你會看到。它只是插入一個串聯的REM命令,所以字符串的其餘部分將被忽略。 – dbenham

+0

@dbenham啊,當然。另一個鬼鬼祟:)的技巧:) – DavidPostill