使用 powershell 拆分字符串以获取第一个和最后一个元素

Split a string with powershell to get the first and last element

如果你这样做:git describe --long

你得到:0.3.1-15-g3b885c5

这就是上面字符串的意思:

标签-CommitDistance-CommitId (http://git-scm.com/docs/git-describe)

如何拆分字符串以获得第一个 (Tag) 和最后一个 (CommitId) 元素?

通过使用 String.split() 和 count 参数来管理 commitid 中的破折号:

$x = "0.3.1-15-g3b885c5"
$tag = $x.split("-",3)[0]
$commitid = $x.split("-",3)[-1]

我不记得标签中是否允许使用破折号,所以我假设它们是,但不会出现在最后两个字段中。

因此:

if ("0.3.1-15-g3b885c5" -match '(.*)-\d+-([^-]+)') {
  $tag = $Matches[1];
  $commitId = $Matches[2]
}

注意:这个答案侧重于改进 split-into-tokens-by-- 方法 ,但请注意,这种方法 并不完全可靠 ,因为 git 标签名称本身可能包含 - 个字符,因此您不能盲目地假设第一个 - 实例结束标签名称。
考虑到这一点,改用


只是为了提供一个更符合 PowerShell 习惯的变体:

# Stores '0.3.1' in $tag, and 'g3b885c5' in $commitId
$tag, $commitId = ('0.3.1-15-g3b885c5' -split '-')[0, -1]
  • PowerShell的-split operator用于通过分隔符-
    将输入字符串拆分为一个令牌数组 [string] 类型的 .Split() 方法 在这里就足够了,.

  • [0, -1]-split 和 [=60= 返回的数组中提取第一个 (0) 和最后一个 (-1) 元素] 它们作为 2 元素数组。

  • $tag, $commitId = 是一个解构多重赋值,它将生成的 2 元素数组的元素分别分配给一个变量。