通过正则表达式匹配循环

Hoo*_*och 30 .net c# regex foreach

这是我的源字符串:

<box><3>
<table><1>
<chair><8>
Run Code Online (Sandbox Code Playgroud)

这是我的Regex Patern:

<(?<item>\w+?)><(?<count>\d+?)>
Run Code Online (Sandbox Code Playgroud)

这是我的Item类

class Item
{
    string Name;
    int count;
    //(...)
}
Run Code Online (Sandbox Code Playgroud)

这是我的物品收藏;

List<Item> OrderList = new List(Item);
Run Code Online (Sandbox Code Playgroud)

我想根据源字符串使用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);
            }
Run Code Online (Sandbox Code Playgroud)

Threre可能是一些小错误,例如在这个例子中丢失信,因为这是我在我的应用程序中更容易的版本.

问题是,最后我在OrderList中只有一个Item.

UPDATE

我搞定了.寻求帮助.

mpe*_*pen 44

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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


Dav*_*rke 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();
Run Code Online (Sandbox Code Playgroud)

随着输出:

比赛清单


drz*_*aus 6

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

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));
Run Code Online (Sandbox Code Playgroud)

这会将所有捕获的值"展平"到单个列表.要维护捕获组,请使用Select而不是SelectMany获取列表列表.