Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# String splitting - breaking string up at second comma

Tags:

string

c#

split

I have a string like so:

mystring = "test1, 1, anotherstring, 5, yetanother, 400";

myarray can be of varying length. What I would like to do is split the string up like so:

{"test1, 1"} 
{"anotherstring, 5}
{"yetanother, 400"}

Is this possible? I tried string[] newArray = mystring.Split(',') but that splits it at every comma, and not the second comma which is what I'd like to do.

Thanks for your help

Zaps

like image 499
Riain McAtamney Avatar asked Jul 15 '10 10:07

Riain McAtamney


1 Answers

You can use a regular expression to match two items in the string:

string[] parts =
  Regex.Matches(myarray[0], "([^,]*,[^,]*)(?:, |$)")
  .Cast<Match>()
  .Select(m => m.Groups[1].Value)
  .ToArray();

This gets the items from the first string in the array. I don't know why you have the string in an array and if you have more than one string, in that case you have to loop through them and get the items from each string.

like image 183
Guffa Avatar answered Sep 20 '22 07:09

Guffa