This is my source string:
<box><3> <table><1> <chair><8>
This is my Regex Patern:
<(?<item>\w+?)><(?<count>\d+?)>
This is my Item class
class Item { string Name; int count; //(...) }
This is my Item Collection;
List<Item> OrderList = new List(Item);
I want to populate that list with Item's based on source string. This is my function. It's not working.
Regex ItemRegex = new Regex(@"<(?<item>\w+?)><(?<count>\d+?)>", RegexOptions.Compiled); foreach (Match ItemMatch in ItemRegex.Matches(sourceString)) { Item temp = new Item(ItemMatch.Groups["item"].ToString(), int.Parse(ItemMatch.Groups["count"].ToString())); OrderList.Add(temp); }
Threre might be some small mistakes like missing letter it this example because this is easier version of what I have in my app.
The problem is that In the end I have only one Item in OrderList.
UPDATE
I got it working. Thans for help.
class Program { static void Main(string[] args) { string sourceString = @"<box><3> <table><1> <chair><8>"; Regex ItemRegex = new Regex(@"<(?<item>\w+?)><(?<count>\d+?)>", RegexOptions.Compiled); foreach (Match ItemMatch in ItemRegex.Matches(sourceString)) { Console.WriteLine(ItemMatch); } Console.ReadLine(); } }
Returns 3 matches for me. Your problem must be elsewhere.
For future reference I want to document the above code converted to using a declarative approach as a LinqPad code snippet:
var sourceString = @"<box><3> <table><1> <chair><8>"; var count = 0; var ItemRegex = new Regex(@"<(?<item>[^>]+)><(?<count>[^>]*)>", RegexOptions.Compiled); var OrderList = ItemRegex.Matches(sourceString) .Cast<Match>() .Select(m => new { Name = m.Groups["item"].ToString(), Count = int.TryParse(m.Groups["count"].ToString(), out count) ? count : 0, }) .ToList(); OrderList.Dump();
With output:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With