Powershell:使用 -split "\s+" 而不是 .split "\s+"

Powershell: using -split "\s+" as opposed to .split "\s+"

序曲

我正在尝试执行一项操作,该操作需要我解析特定文件中的每个单词。最直接的方法是使用以下方式加载文本:

$content = Get-Content -Path .\<filename>

然后我会将每个单独的单词分成单独的一行(这使我可以非常快速地进行字数统计和单个单词搜索)。问题是当我使用这行代码时:

$content.split("\s+")

这应该在每个(一个或多个)空白字符上创建一个新行(拆分)。不幸的是,我的结果是这样的:

$content.split("\s+")
The SpeechSynthe
izer cla

provide
acce

 to the functionality of a 
peech 
ynthe
 i
  engine that i
  in
talled on the ho
t computer. In
talled 
peech 
ynthe
 i
 engine

但是当我运行

$content -split("\s+")

结果会正确出来:

$content -split("\s+")
The
SpeechSynthesizer
class
provides
access
to
the
functionality
of
a
speech
synthesis

我的问题 使用 powershell V.4 我无法理解执行操作之间的区别。

$content.split("\s+")

$content -split("\s+")

是。以及为什么他们输出不同的结果。

这个功能刚刚坏了吗?

这里还有我没有意识到的其他区别吗?

Powershelladmin wiki:

The -split operator takes a regular expression, and to split on an arbitrary amount of whitespace, you can use the regexp "\s+".

To split on a single, or multiple, characters, you can also use the System.String object method Split().

PS C:\> 'a,b;c,d'.Split(',') -join ' | '
a | b;c | d
PS C:\> 'a,b;c,d'.Split(',;') -join ' | '
a | b | c | d

因此,您只是传递了需要使用 $content.split("\s+") 进行拆分的符号,而不是用于匹配空格的正则表达式。

$content -split("\s+")中,\s+是匹配1个或多个空格符号的正则表达式模式