MinhKiyo MinhKiyo - 4 months ago 27
C# Question

How to split string using Regex.Split()

I have one string separated by colons (

:
) as follows:

string str = @"E:\C_Sharp\Projects\Split\test.xlsx:03/08/2016
09:12:56:file name 1,demo1.txt,date create,01/07/2016 09:12:file name
2,demo2.txt,date create,12/07/2016 14:05";


Now I want to split into 4 substring as below:

str1 = @"E:\C_Sharp\Projects\Split\test.xlsx";
str2 = "03/08/2016 09:12:56"
str3 = "file name 1,demo1.txt,date create,01/07/2016 09:12"
str4 = "file name 2,demo2.txt,date create,12/07/2016 14:05"


I used pattern
string pattern = @"\D:\D";
but it can't.

Answer

First of all, your pattern is incorrect. Based on string you've provided, it should be \D:\d|\d:\D, i.e. you want to find occurences of colon surrounded by digit from one side and non-digit from another side.

Second problem is that Regex.Split will remove all occurences of search pattern, so characters around colons at delimiter places will be lost. You can avoid it by replacing delimiter patterns to some character which will never occur in your string and then split by this character.

So you can extract your values like:

string str = @"E:\C_Sharp\Projects\Split\test.xlsx:03/08/2016 09:12:56:file name 1,demo1.txt,date create,01/07/2016 09:12:file name 2,demo2.txt,date create,12/07/2016 14:05";

var values = Regex.Replace(str, @"\D:\d|\d:\D", m => m.Groups[0].Value.Replace(":", "\0"))
                  .Split('\0');
Comments