如何在不为批处理文件中循环分割字符串 [英] How to split string without for loop in batch file

查看:201
本文介绍了如何在不为批处理文件中循环分割字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想分两个部分来分割字符串,而无需使用任何for循环。

I want to split a string in two parts, without using any for loop.

例如,我有一个变量的字符串:

For example, I have the string in a variable:

str=45:abc

我想获得 45 在一个变量和 ABC 中的另一个变量。是否有可能在批处理文件?

I want to get 45 in a variable and abc in another variable. Is it possible in batch file?

模式是像somenumber:somestring

pattern is like somenumber:somestring

推荐答案

您可以在海峡与不同的方式分割。

You could split the str with different ways.

for循环,你不想使用它。

The for loop, you don't want use it.

尾部的部分很容易与 * (匹配任何东西,直到...)结果
设置VAR2 =%STR:*:=%

The trailing part is easy with the * (match anything until ...)
set "var2=%str:*:=%"

领先的部分可以用下流的手段结果进行
设置VAR1 =%STR :: =^&安培; REM#%

The leading part can be done with a nasty trick
set "var1=%str::="^&REM #%

需要插入符号逃脱符号,结果
所以用途不同冒号将&放大器代替; REM#
所以你的情况你得到了线更换后搜索
设置VAR1 = 4567&放大器; REM #abcde 结果
并且这分裂成两个命令

The caret is needed to escape the ampersand,
so effectivly the colon will be replaced by "&REM # So in your case you got the line after replacing
set "var1=4567"&REM #abcde
And this is splitted into two commands

set "var1=4567"
REM #abcde` 

和完整code是在这里:

And the complete code is here:

set "str=4567:abcde"
echo %str%
set "var1=%str::="^&REM #%
set "var2=%str:*:=%"
echo var1=%var1% var2=%var2%

编辑2:更多稳定的主导作用

由于戴夫的主意,用一个换行符。结果
该REM工艺并不反对使用引号和特殊字符的内容非常稳定。结果
但有一个换行符把戏存在一个更稳定的版本时,分裂的说法是比单个字符长也可以工作。

Thanks Dave for the idea to use a linefeed.
The REM technic isn't very stable against content with quotes and special characters.
But with a linefeed trick there exists a more stable version which also works when the split argument is longer than a single character.

@echo off
setlocal enableDelayedExpansion
set ^"str=456789#$#abc"
for /F "delims=" %%a in (^"!str:#$#^=^

!^") do (
  set "lead=%%a"
  goto :break
)
:break
echo !lead!

解决方案3:Adpated dbenhams答案

Dbenh​​am在他的解决方案使用管道换行。结果
这似乎有点过分复杂。结果
由于该解决方案采用的事实,解析器的转义换行后删除该行的其余部分(当此之前或在特别发现字符相)。

Dbenham uses in his solution a linefeed with a pipe.
This seems a bit over complicated.
As the solution uses the fact, that the parser removes the rest of the line after an unescaped linefeed (when this is found before or in the special character phase).

起初冒号用以延迟扩展更换一个换行符。结果
被允许,现在换行是变量的部分。结果,
然后行设置铅=%的铅%去除结尾的部分。结果
最好不要在这里使用扩展语法,如设置铅=%的铅%如果报价是字符串的一部分将打破。

At first the colon character is replaced to a linefeed with delayed expansion replacement.
That is allowed and the linefeed is now part of the variable.
Then the line set lead=%lead% strips the trailing part.
It's better not to use the extended syntax here, as set "lead=%lead%" would break if a quote is part of the string.

setlocal enableDelayedExpansion
set "str=45:abc"
set ^"lead=!str::=^

!"
set lead=%lead%
echo "!lead!"

这篇关于如何在不为批处理文件中循环分割字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆