如何批量拆分变量到数组中

时间:2016-09-07 23:16:18

标签: arrays batch-file

我正在尝试批量编写文本冒险,所以我想知道如何分割变量,如set userinput = take book并将其转换为数组。我希望能够编写一个程序,将字符串拆分为每个空格中的数组项。我用很多其他语言做过这个。还有其他几个这样的问题,但我不觉得他们回答了我的问题。

1 个答案:

答案 0 :(得分:3)

这项任务可能比你意识到的要困难得多。有很多“简单”的方法,但没有一个是简单的方法。

例如,一个简单的FOR循环可以解析单个标记,但它会被*?"打破。

强大的解决方案需要大量代码。

这是我的解决方案,有广泛的评论:

@echo off

:: Start out with delayed expansion disabled, and define "user input"
:: I intentionally include "problem" characters
setlocal disableDelayedExpansion
set "userinput=take book! & ;MustPreserve    EmptyLinesAreIgnored"

:: Initialize count
set "cnt=0"

:: Enable and use delayed expansion to protect against poison characters
setlocal enableDelayedExpansion

:: Substitute <LineFeed> for each <space>
(set parsed=!userinput: =^
%= Do not remove or alter this line =%
!)

:: Iterate each line, setting delims and eol to <space> to preserve all tokens
for /f "eol= delims= " %%A in ("!parsed!") do (

  %= Return to delayed expansion disabled on first iteration, else ! is lost =%
  if "!" equ "" endlocal

  %= Increment the count =%
  set /a cnt+=1

  %= Temporarily enable delayed expansion to capture current count in FOR variable =%
  setlocal enableDelayedExpansion
  for %%N in (!cnt!) do (
    endlocal

    %= Save the array value =%
    set "token.%%N=%%A"
  )
)

::Print the results. Safe array access requires delayed expansion
setlocal enableDelayedExpansion
for /l %%N in (1 1 !cnt!) do echo token.%%N=!token.%%N!

没有所有评论,它看起来好一点

@echo off
setlocal disableDelayedExpansion
set "userinput=take book! & :MustPreserveColon ;MustPreserve    EmptyLinesAreIgnored"

set "cnt=0"
setlocal enableDelayedExpansion
(set parsed=!userinput: =^
%= Do not remove or alter this line =%
!)
for /f "eol= delims= " %%A in ("!parsed!") do (
  if "!" equ "" endlocal
  set /a cnt+=1
  setlocal enableDelayedExpansion
  for %%N in (!cnt!) do (
    endlocal
    set "token.%%N=%%A"
  )
)

setlocal enableDelayedExpansion
for /l %%N in (1 1 !cnt!) do echo token.%%N=!token.%%N!

这是输出:

token.1=take
token.2=book!
token.3=&
token.4=;MustPreserve
token.5=EmptyLinesAreIgnored