Arvind chaudhary Arvind chaudhary - 21 days ago 7
C# Question

Split and reformat a String using Regex

I have a string variable like:

string data= "#FirstName=Arvind #LastName= Chaudhary_009"


Using Regex in C# i Want the output like :

FirstName = Arvind;
LastName= Chaudhary009;

Answer

There would be more ways of doing this. Two of them would be

string data = "#FirstName=Arvind #LastName= Chaudhary_009";
data = data.Replace("_", "");
data = data.Replace("=", " = ");
string[] dt = data.Split(new char[] {'#'}, StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine(dt[0]); // Print your array here

Regex: Which you asked for

Regex regex = new Regex(@"#");
string[] dt1 = regex.Split(data).Where(s => s != String.Empty).ToArray();
Console.WriteLine(dt1[0]); // Print your array here

You can print array the way you want

Edit

After Understanding the requirements from comments

string data = "#FirstName=Arvind #LastName= Chaudhary_009";
data = data.Replace("_", "");
string[] dt = data.Split(new char[] {'#'}, StringSplitOptions.RemoveEmptyEntries);

Regex regex = new Regex(@"#");
string[] dt1 = regex.Split(data).Where(s => s != String.Empty).ToArray();

foreach(string d in dt)
{
    //this will print both the line
    Console.WriteLine(d);
}

foreach(string d in dt1)
{
    //this will print both the line
    Console.WriteLine(d);
}

Screenshot for showing the output

Comments