简体   繁体   中英

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;

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);
}

显示输出的屏幕截图

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM