【问题标题】:Powershell to split a string into an array by start and end charactersPowershell通过开始和结束字符将字符串拆分为数组
【发布时间】:2020-10-19 18:35:08
【问题描述】:

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

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

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

【问题讨论】:

  • ($mystring -replace '=|;').Split(' ') 适用于这种情况。 $mystring.Split("=").Split(";").Trim() -ne '' 也有效。 ($mystring -replace ' ?=|;').ToCharArray()

标签: arrays powershell split


【解决方案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)

【讨论】:

    【解决方案2】:

    大卫,你的东西看起来不错,但这里是另一种方法。 -replace 方法处理空格 (" ") 和等号 (=)。

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

    【讨论】:

      猜你喜欢
      • 2020-10-22
      • 2018-11-14
      • 1970-01-01
      • 1970-01-01
      • 2013-02-26
      • 1970-01-01
      • 2016-10-14
      • 1970-01-01
      • 2017-09-21
      相关资源
      最近更新 更多