Home > database >  How to extract a string from a string between specific Chars in C#?
How to extract a string from a string between specific Chars in C#?

Time:12-04

I want to extract specific string from a string between these chars "@" and "#".

For example my string is

string myStr= "*-34@Apple#*-42@Banana#*-42@Orange#........";

I Want to extract Apple, Banana, Orange from the string!

Note: I need solution with dynamic approach as myStr length can be variable

CodePudding user response:

Using MatchCollection we can try:

string myStr = "*-34@Apple#*-42@Banana#*-42@Orange#*........";
MatchCollection matches = Regex.Matches(myStr, "-\\d @(.*?)#\\*");
Console.WriteLine("There were {0} matches:", matches.Count);
foreach (Match match in matches) {
    Console.WriteLine(match.Groups[1].Value);
}

This prints:

There were 3 matches:
Apple
Banana
Orange
  • Related