Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...