仅在角色的第一次出现时分开

Luc*_*man 4 powershell

如果我有一个字符串

foo:bar baz:count
Run Code Online (Sandbox Code Playgroud)

我想在第一次出现时拆分:并获得一个返回的数组,其中只包含两个元素:

  • 一个字符串,它是第一个冒号之前的元素.
  • 一个字符串,它是第一个冒号后的所有内容.

我怎样才能在Powershell中实现这一目标?

use*_*407 14

-split 运算符允许您指定要返回的最大子串数:

'foo:bar baz:count' -split ':',2
Run Code Online (Sandbox Code Playgroud)


Chr*_*s L 2

用于IndexOf()查找第一次出现的 ':'

获取从开头到“:”索引的子字符串

取出字符串中从“:”到末尾的其余部分。

代码:

$foobar = "foo:bar baz:count"
$pos = $foobar.IndexOf(":")
$leftPart = $foobar.Substring(0, $pos)
$rightPart = $foobar.Substring($pos+1)
Run Code Online (Sandbox Code Playgroud)