Powershell split() 与 -split - 有什么区别? [英] Powershell split() vs -split - what's the difference?
问题描述
在为此苦苦挣扎了半个小时之后,我在用空格拆分字符串时遇到了这种差异,具体取决于您使用的语法.
After struggling with this for half an hour, I've experienced this difference when splitting a string with spaces, depending on which syntax you use.
简单字符串:
$line = "1: 2: 3: 4: 5: "
拆分示例 1 - 请注意从 1 开始带有标记的额外空间:
Split example 1 - notice the extra space with tokens from 1 onwards:
$ln = $line.split(":\s+")
$ln
1
2
3
4
5
拆分示例 2 - 空格不见了(应该如此)
Split example 2 - the spaces are gone (as they should)
$ln = $line -split ":\s+"
$ln
1
2
3
4
5
我怀疑这是因为第一个是 .NET 方法 (?),而 -split
PS 运算符在正则表达式解释方面可能具有更多的智能.
I suspect it's because the first one is a .NET method (?), and the -split
PS operator perhaps has more baked-in smarts when it comes to regex interpretation.
但是,当我尝试使用像 ": "
这样的拆分的第一种方法时,它也无法正常工作.如果它是 .NET,它是否需要一些东西来正确解释它应该使用两个字符作为分隔符的事实?
However, when I tried the first method with the split like ": "
, that didn't work properly either. If it's .NET, does it need something to correctly interpret the fact it should be using both characters as a delimiter?
推荐答案
The .Net System.String.Split 方法没有采用字符串形式的单个参数的重载.它也不理解正则表达式.
The .Net System.String.Split method does not have an overload that takes a single parameter that is a string. It also does not understand regex.
发生的事情是 powershell 正在获取您传入的字符串并将其转换为字符数组.它本质上是在以下字符处拆分 :
, \
, s
, +
What is happening is that powershell is taking the string you are passing in and converting it to an array of characters. It is essentially splitting at the following characters :
, \
, s
, +
当您使用 ": "
作为分隔符时,我想您会得到类似
When you use ": "
as the delimiter, I would imagine you got results like
1
2
3
4
5
这是因为没有为 .Net 方法指定字符串拆分选项,它将包含在相邻分隔符之间找到的空字符串.
That is because without specifying a string split option to the .Net method, it will include empty strings that it finds between adjacent separators.
这篇关于Powershell split() 与 -split - 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!