String.Split() 的奇怪结果 [英] Strange result from String.Split()
问题描述
为什么下面的结果是一个有 7 个元素和 5 个空白的数组?我希望只有 2 个元素.5个空白元素从何而来?
Why does the following result in an array with 7 elements with 5 blank? I'd expect only 2 elements. Where are the 5 blank elements coming from?
$a = 'OU=RAH,OU=RAC'
$b = $a.Split('OU=')
$b.Count
$b
<#
Outputs:
7
RAH,
RAC
#>
推荐答案
它为分隔符中的每个字符拆分字符串.所以它把它分成'O','U' &'='.
It splits the string for each character in the separator. So its splitting it on 'O', 'U' & '='.
正如@mklement0 所评论的,我之前的回答并不适用于所有情况.因此,这是获取预期项目的另一种方法.
As @mklement0 has commented, my earlier answer would not work in all cases. So here is an alternate way to get the expected items.
$a.Split(',') |% { $_.Split('=') |? { $_ -ne 'OU' } }
此代码将拆分字符串,首先在 、
上拆分,然后在 =
上拆分每个项目并忽略 OU
的项目,最终返回预期值:
This code will split the string, first on ,
then each item will be split on =
and ignore the items that are OU
, eventually returning the expected values:
RAH
RAC
即使在以下情况下也能工作:
This will work even in case of:
$a = 'OU=FOO,OU=RAH,OU=RAC'
生成 3 个项目 FOO
, RAH
&RAC
generating 3 items FOO
, RAH
& RAC
要按预期仅获得 2 个字符串,您可以使用以下行:$a.Split('OU=', [System.StringSplitOptions]::RemoveEmptyEntries)这将使输出为:拉赫,RAC如果您使用(注意分隔符中的逗号)$a.Split(',OU=', [System.StringSplitOptions]::RemoveEmptyEntries)你会得到RAHRAC
这可能就是你想要的.:)
This is probably what you want. :)
这篇关于String.Split() 的奇怪结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!