【发布时间】:2015-08-17 12:36:14
【问题描述】:
我有一个字符串,我使用代码$CreateDT.Split(" ") 对其进行了拆分。我现在想以不同的方式操作两个单独的字符串。如何将它们分成两个变量?
【问题讨论】:
标签: string powershell
我有一个字符串,我使用代码$CreateDT.Split(" ") 对其进行了拆分。我现在想以不同的方式操作两个单独的字符串。如何将它们分成两个变量?
【问题讨论】:
标签: string powershell
像这样?
$string = 'FirstPart SecondPart'
$a,$b = $string.split(' ')
$a
$b
【讨论】:
"FirstPart SecondPart ThirdPart"并且只想要两个,你可以使用$a,$b = $string.split(' ')[0,1]
使用-split 运算符创建一个数组。像这样,
$myString="Four score and seven years ago"
$arr = $myString -split ' '
$arr # Print output
Four
score
and
seven
years
ago
当你需要某个项目时,使用数组索引来到达它。请注意,索引从零开始。像这样,
$arr[2] # 3rd element
and
$arr[4] # 5th element
years
【讨论】:
$arr = @($myString.split(' '))
$first_word = ("one-two-three" -split '-')[0]
.Split() 总是返回一个数组,因此不需要@(...):$arr = $myString.split(' '),但请注意,更符合 PowerShell 惯用的解决方案 $arr = $myString -split ' ' 已经是答案。但是请注意,-split 采用 regex 并且不区分大小写(使用 -csplit 进行区分大小写的拆分)。
请务必注意这两种技术之间的以下区别:
$Str="This is the<BR />source string<BR />ALL RIGHT"
$Str.Split("<BR />")
This
is
the
(multiple blank lines)
source
string
(multiple blank lines)
ALL
IGHT
$Str -Split("<BR />")
This is the
source string
ALL RIGHT
由此可以看出string.split()方法:
而-split 运营商:
【讨论】:
-split 将 regex(正则表达式)作为其(第一个)RHS 操作数,而 [string] 类型的 .Split() 方法对 literal 字符 / 字符数组 / 和 - 在 .NET Core 中 - 也是文字 string。另外,请注意 PowerShell 中的正确语法是 $Str -split '<BR />';虽然伪方法语法$Str -Split("<BR />")碰巧在这种情况下有效,但应该避免。
试试这个:
$Object = 'FirstPart SecondPart' | ConvertFrom-String -PropertyNames Val1, Val2
$Object.Val1
$Object.Val2
【讨论】:
ConvertFrom-String 已经过时,应该避免使用(它总是给人一种实验性的感觉,而且它还没有包含在 PowerShell Core 中的事实表明它不会继续存在)。至于是否需要额外操作:解构赋值即可:$val1, $val2 = 'FirstPart SecondPart' -split ' '
ConvertFrom-String 的所有固有 问题都足以避免它。这尤其适用于基于模板的解析,但即使是基于分隔符的解析也存在缺陷,因为 类型推断 总是 应用 - 请参阅stackoverflow.com/a/50166580/45375。跨度>
foreach-object 操作语句:
$a,$b = 'hi.there' | foreach split .
$a,$b
hi
there
【讨论】: