dauzduz TV
dauzduz TV

Reputation: 69

I try to get all data included in [] (not specific tokens!)

I try to get all data included in [] (not specific tokens!) I try with loop but its give only 1 parameter.

Example what I need:

set "x=Stackoverflow [I need it] and [I need this too] and [this too]"

output => I need it, I need this too, this too

Tried to do:

  for /f "delims=[]" %%a in ("%x%") do (
      echo %%a
  )

Upvotes: 0

Views: 58

Answers (2)

Aacini
Aacini

Reputation: 67216

A very simple method:

@echo off
setlocal EnableDelayedExpansion

set "x=Stackoverflow [I need it] and [I need this too] and [this too]"

set "output=" & set "p=%x:]=" & set "output=!output!, !p:*[=!" & set "p=%"

echo output =^> %output:~2%

Output:

output => I need it, I need this too, this too

For an explanation of the method used, you should remove the @echo off line, run the program and carefully review the executed code. If you want further explanations, then review this topic.

Upvotes: 0

Stephan
Stephan

Reputation: 56188

you could use "tokens=2,4,6,8,10,12 delims=[]", but it is difficult to post-process the result (removing additional commas/spaces).
The same effect can be reached by preprocessing the string and splitting with a plain for loop. The flag variable takes care of using each second token only. I added a _ in front of the string to correctly process strings that start with a [. set /a "flag=(flag+1) %% 2" alternates the flag variable between 0 and 1.

@echo off
setlocal enabledelayedexpansion
set "x=[this] not [that] not [yes] no [in] out"
set "y=_%x:[=","%"
set "y=%y:]=","%"

set flag=0
for %%a in ("%y%") do (
  if !flag!==1 set "result=!result!, %%~a"
  set /a "flag^=1"
)
if defined result set "result=%result:~2%"
echo output = %result%

Output:

output = this, that, yes, in

Upvotes: 1

Related Questions