Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only split on the first occurence of a character

Tags:

powershell

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:

  • A string which is the element before the first colon.
  • A string which is everything after the first colon.

How can I achieve this in Powershell?

like image 571
Lucas Kauffman Avatar asked Jul 13 '15 09:07

Lucas Kauffman


People also ask

How do you split a string with the first occurrence of a character in python?

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 .

How do I split a string at first?

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!

What is the default split character for the split () string method?

The split() method splits a string into a list. You can specify the separator, default separator is any whitespace.

How do you find the first occurrence of a character in a string in Javascript?

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.


2 Answers

-split operator allows you to specify maximum number of substrings to return:

'foo:bar baz:count' -split ':',2
like image 190
user4003407 Avatar answered Nov 04 '22 20:11

user4003407


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)
like image 37
Chris L Avatar answered Nov 04 '22 21:11

Chris L