I'll assume your string is in a variable - I'll call it string, and you want to put the value in variable val.
If the first and second [tags] are always as you have in your example, and no possibility of other [ or ] before [SNUM], then
for /f "delims=[] tokens=3" %%A in ("X%string%") do set "val=%A"
The leading X is added to ensure the correct value is extracted regardless whether the string includes any characters before [idnum].
If the above can't be used because the string does not have a fixed format, then the following can be used provided that
- the value does not contain an odd number of quotes
- there are no poison characters between quotes within the original string.
- it is safe to ignore case when identifying [tags]
set "val=%string:*[idnum]=%"
set "val=%val:[snum]="&rem %
The first set becomes set "val=123456[SNUM]00001[DATEC]01012020[END]"
The second set becomes set "val=123456"&rem 00001[DATEC]01012020[END]
It should be obvious how that gives the correct value.
Lastly, here is a robust solution that should always work as long as you don't run into maximum string length issues, and the [tags] are not case sensitive.
setlocal disableDelayedExpansion
setlocal enableDelayedExpansion
:: escape \ and | characters
set "val=!string:\=\S!"
set "val=!val:|=\P!"
:: convert [idnum] and [snum] to |
set "val=!val:[idnum]=|!"
set "val=!val:[snum]=|!"
:: parse out the value. delayed expansion is toggled off so it does not corrupt any `!` that might appear within the value
for /f "tokens=2 delims=|" %%A in ("X!val!") do (
endlocal
set "val=%%A"
)
:: restore any \ and |
setlocal enableDelayedExpansion
set "val=!val:\P=|!"
set "val=!val:\S=\!"
If you know that the string can never contain | (or some other character), then it is much simpler:
setlocal disableDelayedExpansion
setlocal enableDelayedExpansion
set "val=!string:[idnum]=|!"
set "val=!string:[snum]=|!"
for /f "tokens=2 delims=|" %%A in ("X!val!") do (
endlocal
set "val=%%A"
)
FOR /F "tokens=3 delims=[]" %A IN ("str=[IDNUM]123456[SNUM]00001[DATEC]01012020[END]") DO @ECHO %A. In a batch file, use%%Ainstead of%A.set "str=[IDNUM]123456[SNUM]00001[DATEC]01012020[END]"FOR /F "tokens=2 delims=[]" %%A IN ("%str%") DO @ECHO %%A