拆分here-string时清空字符串

时间:2014-08-13 13:11:22

标签: string powershell powershell-v3.0

来自另一个SO question的衍生问题。

在carridge上分割here-string时返回+换行[backtick] r [backtick] n我希望得到以下结果

$theString = @"
word
word
word
word
word
"@

$theString.Split("`r`n") | Measure-Object

Count    : 5
Average  : 
Sum      : 
Maximum  : 
Minimum  : 
Property : 

相反,我得到的是以下输出

Count    : 9
Average  : 
Sum      : 
Maximum  : 
Minimum  : 
Property : 

额外的4个对象是空字符串。正在运行%{ $_.GetType().FullName}会显示System.String类型的所有项目。在上述SO问题中,答案解释了空字符串。我试图理解为什么它们是从分裂中创建的,当我不期望它们是。

2 个答案:

答案 0 :(得分:2)

String.Split()分割匹配模式中指定的任何字符,因为`r`n是两个字符,你得到:

word`r    
`n    
word`r    
`n

不要直接在代码中指定字符,而是使用.NET System.Environment enumeration's NewLine member。然后使用System.StringSplitOptions删除所有空条目。

$theString.Split([System.Environment]::NewLine, [System.StringSplitOptions]::RemoveEmptyEntries) |
    measure-object

答案 1 :(得分:2)

我通常推荐@alroc的解决方案。另一种方法是使用-split运算符。

PS P:\> $theString = @"
word
word
word
word
word
"@

$theString -split "`r`n" | Measure-Object
$theString -split [environment]::NewLine | Measure-Object


Count    : 5
Average  : 
Sum      : 
Maximum  : 
Minimum  : 
Property : 

Count    : 5
Average  : 
Sum      : 
Maximum  : 
Minimum  : 
Property :