If I have a string like
foo:bar baz:count
and I want to split on the first occurrence of :
and get an array returned which contains only two elements:
How can I achieve this in Powershell?
Use the str. split() method with maxsplit set to 1 to split a string on the first occurrence, e.g. my_str. split('-', 1) . The split() method only performs a single split when the maxsplit argument is set to 1 .
To split a string and get the first element of the array, call the split() method on the string, passing it the separator as a parameter, and access the array element at index 0 . For example, str. split(',')[0] splits the string on each comma and returns the first array element. Copied!
The split() method splits a string into a list. You can specify the separator, default separator is any whitespace.
The indexOf() method returns the position of the first occurrence of a value in a string. The indexOf() method returns -1 if the value is not found. The indexOf() method is case sensitive.
-split
operator allows you to specify maximum number of substrings to return:
'foo:bar baz:count' -split ':',2
Using IndexOf()
to find first occurance of ':'
Take the substring from the beginning until the index of ':'
Take the rest of the string from the ':' to the end.
Code:
$foobar = "foo:bar baz:count"
$pos = $foobar.IndexOf(":")
$leftPart = $foobar.Substring(0, $pos)
$rightPart = $foobar.Substring($pos+1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With