通过正则表达式匹配循环

时间:2011-04-23 23:15:43

标签: c# .net regex foreach

这是我的源字符串:

<box><3>
<table><1>
<chair><8>

这是我的Regex Patern:

<(?<item>\w+?)><(?<count>\d+?)>

这是我的Item类

class Item
{
    string Name;
    int count;
    //(...)
}

这是我的物品收藏品;

List<Item> OrderList = new List(Item);

我想根据源字符串使用Item填充该列表。 这是我的功能。它不起作用。

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可能是一些小错误,例如在这个例子中丢失信,因为这是我在我的应用程序中更容易的版本。

问题是最终我在OrderList中只有一个Item。

更新

我得到了它的工作。 寻求帮助。

3 个答案:

答案 0 :(得分:39)

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();
    }
}

为我返回3场比赛。你的问题必须在其他地方。

答案 1 :(得分:11)

为了将来的参考,我想记录上面转换为使用声明方法的代码作为LinqPad代码片段:

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();

输出:

List of matches

答案 2 :(得分:5)

要解决问题的标题(“循环使用正则表达式匹配”),您可以:

var lookfor = @"something (with) multiple (pattern) (groups)";
var found = Regex.Matches(source, lookfor, regexoptions);
var captured = found
                // linq-ify into list
                .Cast<Match>()
                // flatten to single list
                .SelectMany(o =>
                    // linq-ify
                    o.Groups.Cast<Capture>()
                        // don't need the pattern
                        .Skip(1)
                        // select what you wanted
                        .Select(c => c.Value));

这会将所有捕获的值“展平”到一个列表。要维护捕获组,请使用Select而不是SelectMany来获取列表列表。