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

安稳与你 提交于 2020-01-03 08:57:10

问题


If you do: git describe --long

you get: 0.3.1-15-g3b885c5

Thats the meaning of the above string:

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

How would you split the string to get the first (Tag) and last (CommitId) element?


回答1:


By using String.split() with the count parameter to manage dashes in the commitid:

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



回答2:


Note: This answer focuses on improving on the split-into-tokens-by-- approach from Ocaso Protal's helpful answer.
However, that approach isn't fully robust, because git tag names may themselves contain - characters, so you cannot blindly assume that the first - instance ends the full tag name.
To account for that, use Richard's robust solution instead.


Just to offer a more PowerShell-idiomatic variant:

$tag, $commitId = ('0.3.1-15-g3b885c5' -split '-')[0, -1]
  • PowerShell's -split operator is used to split the input string into an array of tokens by separator -
    While the [string] type's .Split() method would be sufficient here, -split offers many advantages in general.

  • [0, -1] extracts the first (0) and last (-1) element from the array returned by -split and returns them as a 2-element array.

  • $tag, $commitId = is a destructuring assignment that assigns the elements of the resulting 2-element array to a variable each.




回答3:


I can't recall if dashes are allowed in tags, so I'll assume they are, but will not appear in the last two fields.

Thus:

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


来源:https://stackoverflow.com/questions/32095674/split-a-string-with-powershell-to-get-the-first-and-last-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!