如何使用分隔符作为整个单词使用cmd bat拆分String

时间:2018-01-10 11:01:29

标签: batch-file split

如何使用delim = string拆分字符串 E.g:

拆分字符串

"sssssMssssMYSTR___M___MYSTRzzzzzzMzzzz"

通过

delim="MYSTR" 

,结果应为:

sssssMssss
___M___
zzzzzzMzzzz

此类代码

for /f "tokens=1,2 delims=MYSTR" %%A in ("sssssMssssMYSTR___M___MYSTRzzzzzzMzzzz") do (
         set fn1=%%A
     )

不起作用/它仅使用'M'的第一个字母进行分割

如何按字词分割?

2 个答案:

答案 0 :(得分:0)

尝试使用split.bat(您可以将它们用作函数或单独的bat文件(不能很好地处理!%")):

@echo off
setlocal
call :split "sssssMssssMYSTR___M___MYSTRzzzzzzMzzzz" MYSTR 1 spl1
echo %spl1%
call :split "sssssMssssMYSTR___M___MYSTRzzzzzzMzzzz" MYSTR 2 spl2
echo %spl2%
call :split "sssssMssssMYSTR___M___MYSTRzzzzzzMzzzz" MYSTR 3
rem echo %spl2%

endlocal & exit /b %errorlevel%


:split [%1 - string to be splitted;%2 - split by;%3 - possition to get; %4 - if defined will store the result in variable with same name]
::http://ss64.org/viewtopic.php?id=1687

setlocal EnableDelayedExpansion

set "string=%~2%~1"
set "splitter=%~2"
set /a position=%~3

set LF=^


rem ** Two empty lines are required
echo off
for %%L in ("!LF!") DO (
    for /f "delims=" %%R in ("!splitter!") do ( 
        set "var=!string:%%~R%%~R=%%~L!"
        set "var=!var:%%~R=%%~L!"
        if "!var!" EQU "!string!" (
            echo "%~1" does not contain "!splitter!" >&2
            exit /B 1
        )
    )
)

if "!var!" equ "" (
    endlocal & if "%~4" NEQ "" ( set "%~4=")
)
if !position! LEQ 0 ( set "_skip=" ) else (set  "_skip=skip=%position%")

for /f  "eol= %_skip% delims=" %%P in ("!var!") DO (
    if "%%~P" neq "" ( 
        set "part=%%~P" 
        goto :end_for 
    )
)
set "part="
:end_for
if not defined part (
 endlocal
 echo Index Out Of Bound >&2 
 exit /B 2
)
endlocal & if "%~4" NEQ "" (set %~4=%part%) else echo %part%
exit /b 0

答案 1 :(得分:0)

@echo off
setlocal EnableDelayedExpansion

set "string=sssssMssssMYSTR___M___MYSTRzzzzzzMzzzz"

rem Do the split:
set i=1
set "fn!i!=%string:MYSTR=" & set /A i+=1 & set "fn!i!=%"

set fn

输出:

fn1=sssssMssss
fn2=___M___
fn3=zzzzzzMzzzz

您可以查看this topic以获取有关所用方法的详细说明......