Arvind chaudhary
Arvind chaudhary

Reputation: 39

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;

Upvotes: 0

Views: 58

Answers (2)

Mohit S
Mohit S

Reputation: 14064

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

Upvotes: 1

Dustin S.
Dustin S.

Reputation: 46

There will be many solutions. I suggest you use .NET Regex Tester or a similar online tool to help develop a regex that works well.

A simple example regex that will give you some groups:

#FirstName\s*=\s*(.*)\s?#LastName\s*=\s*(.*)_(.*)

Run that and then format up the output based on groups 1, 2, 3.

Upvotes: 0

Related Questions