抱歉,如果这是一个明显的,但我已经尝试了很多东西来使这项工作...在VB(我更熟悉),我相信它会没事的.
我正在尝试拆分带有" - "分隔符的字符串.空间是至关重要的,因为字符串中的'其他地方',但不是分隔.
"This-string - contains - some-hyphens".Split(' - ')
Run Code Online (Sandbox Code Playgroud)
这应该(在我的大脑中)返回3个元素:
This-string contains some-hyphens
不幸的是,我获得了9个以上的元素,具体取决于我如何使用该Split方法.
This string contains some hyphens
它显然-单独分裂,但似乎也在空间上分裂,而忽略了' - '格式.
Major Minor Build Revision ----- ----- ----- -------- 5 1 17134 228
String.Split你使用接受的方法超载char[],所以powershell很好,并为你分割你的字符串.如果要使用字符串,则需要传递StringSplitOptions:
'This-string - contains - some-hyphens'.Split((,' - '), [StringSplitOptions]::RemoveEmptyEntries)
Run Code Online (Sandbox Code Playgroud)
在测试中,我需要使用一元数组运算符,来强制解析器使用正确的重载.
powershell-esque方式更多的是使用-split使用正则表达式操作的运算符:
'This-string - contains - some-hyphens' -split ' - '
Run Code Online (Sandbox Code Playgroud)