Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through Regex Matches

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.

like image 284
Hooch Avatar asked Apr 23 '11 23:04

Hooch


2 Answers

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.

like image 127
mpen Avatar answered Oct 02 '22 10:10

mpen


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:

List of matches

like image 44
David Clarke Avatar answered Oct 02 '22 10:10

David Clarke