39

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.

Hooch
  • 28,817
  • 29
  • 102
  • 161

2 Answers2

54
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.

mpen
  • 272,448
  • 266
  • 850
  • 1,236
12

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

David Clarke
  • 12,888
  • 9
  • 86
  • 116
  • What program is on that screenshot? Is it your own program? – Hooch Dec 14 '11 at 20:16
  • 1
    That's generated by LinqPad's Dump() extension method. You can stick Dump() on the end of most objects and it will output a formatted representation of the object. LinqPad is just an exceptional tool for writing/evaluating C# code http://www.linqpad.net/. The above code can be copied and pasted straight into LinqPad and it will generate the table. – David Clarke Dec 14 '11 at 22:29
  • 1
    Then I'm all like, lawl... I'm going to click "edit" to see the markdown for making such a pretty table. – Suamere Sep 05 '17 at 13:32