Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: String split returning list of strings AND list of delimiters?

Tags:

string

c#

split

Is there any inbuilt way in C# to split a text into an array of words and delimiters? What I want is:

text = "word1 + word2 - word3";
string[] words = text.Split(new char[] { '+', '-'});
//Need list '+', '-' here?

Any ideas? Obviously I can just process the text by hand... :)

like image 612
Andrew White Avatar asked Jan 22 '23 22:01

Andrew White


1 Answers

Use Regex.split() with capturing parentheses http://msdn.microsoft.com/en-us/library/byy2946e.aspx

string input = @"07/14/2007";   
string pattern = @"(-)|(/)";

foreach (string result in Regex.Split(input, pattern)) 
{
   Console.WriteLine("'{0}'", result);
}
// In .NET 1.0 and 1.1, the method returns an array of
// 3 elements, as follows:
//    '07'
//    '14'
//    '2007'
//
// In .NET 2.0, the method returns an array of
// 5 elements, as follows:
//    '07'
//    '/'
//    '14'
//    '/'
//    '2007'
like image 162
Sijin Avatar answered Jan 24 '23 11:01

Sijin