Powershell通过开始和结束字符将字符串拆分为数组

时间:2020-06-29 14:52:16

标签: arrays powershell split

给出要从字符串中提取的值(其中每个值都由起始字符和结束字符包围),最有效的方法是什么?

例如,要获取包含值的数组:a b c

$mystring = "=a; =b; =c;"
$CharArray = $mystring.Split("=").Split(";")

2 个答案:

答案 0 :(得分:1)

有许多-replace-split.Split().Replace()的组合可用于此任务。以下是一些示例:

# Since each element is separated by a space, you can replace extraneous characters first
# -split operator alone splits by a space character
# This can have issues if your values contain spaces too
($mystring -replace '=|;').Split(' ')
-split ($mystring -replace '=|;')

# Since splitting creates white space at times, `Trim()` handles that.
# Because you expect an array after splitting, -ne '' will only return non-empty elements
$mystring.Split("=").Split(";").Trim() -ne ''

# Creates a array of of System.Char elements. Take note of the type here as it may not be what you want.
($mystring -replace ' ?=|;').ToCharArray()

# Uses Split(String[], StringSplitOptions) method
($myString -replace ' ?=').Split(';',[StringSplitOptions]::RemoveEmptyEntries)

答案 1 :(得分:1)

大卫,您看起来不错,但是这里还有另一种方法。 -replace方法处理空格(“”)和等号(=)。

$mystring = "=a; =b; =c;"
$CharArray = $mystring -split ";" -replace " |=",""