批处理脚本 - 用括号拆分字符串

时间:2014-03-26 01:57:39

标签: string batch-file split cmd

在Windows批处理脚本中,我需要将括号中的用户名和用户ID以及括号中可能的非员工状态的字符串拆分为仅逗号分隔的userID列表。

SET INPUT = Stone,Jake(非empl)(stonej),Smith,John(smithj),Doe Milton,Jane(doej)

OUTPUT = stonej,smithj,doej

有人可以帮忙吗?

3 个答案:

答案 0 :(得分:0)

这解决了任务 - 但如果实际任务是转换文件,它将会改变 这应该处理普通批处理代码会出现问题的字符。

这使用名为repl.bat的帮助程序批处理文件 - 从https://www.dropbox.com/s/qidqwztmetbvklt/repl.bat

下载

repl.bat放在与批处理文件相同的文件夹中或放在路径上的文件夹中。

@echo off
set "input=Stone, Jake (non-empl) (stonej), Smith, John (smithj), Doe Milton, Jane (doej)"

for /f "delims=" %%a in ('echo "%input%,"^|repl "\(non-empl\)" "" ^|repl ".*?\((.*?)\).*?," "$1," ^|repl "..$" "" ') do set output=%%a
echo "%output%"
pause

答案 1 :(得分:0)

@echo off

SET INPUT=Stone, Jake (non-empl) (stonej), Smith, John (smithj), Doe Milton, Jane (doej)

for /F "tokens=4,6,8 delims=()" %%a in ("%input%") do set OUTPUT=%%a,%%b,%%c
echo OUTPUT=%OUTPUT%

输出:

OUTPUT=stonej,smithj,doej

答案 2 :(得分:0)

这是一个本机批处理文件解决方案

@echo off
setlocal enableDelayedExpansion
set "input=Stone, Jake (non-empl) (stonej), Smith, John (smithj), Doe Milton, Jane (doej)"

:: Define LF to contain a linefeed character
set ^"LF=^

^" Above empty line is critical - DO NOT REMOVE

:: Remove (non-empl) from data
set "input=!input:(non-empl)=!"

:: insert linefeed before ( and after )
for %%L in ("!LF!") do (
  set "input=!input:(=%%~L(!"
  set "input=!input:)=)%%~L!"
)

:: Echo the value and pipe to FINDSTR to preserve lines containing (
:: Must delay expansion by escaping !, and use CMD /V:ON to re-enable delayed expansion
:: Use FOR /F to parse the result, discarding ( and ), and build output
for /f "delims=()" %%A in ('cmd /v:on /c echo ^^!input^^!^|findstr "("') do set output=!output!%%A,

:: Remove unwanted trailing , from output
set "output=!output:~0,-1!"

:: Show result
echo output=!output!